﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Collections.ObjectModel;
using Portal.Cms.Model;
using Portal.Web.Utility;
using Portal.Database.Service;
using Portal.Core;
using Portal.Utility;
using DtSearchIndexService;
using Portal.Workflow.Bussiness;
using System.Data.SqlClient;
using Portal.Cms.Bussiness.Template;
using Portal.Systems.Model;

namespace Portal.Cms.Bussiness
{
    public class CmsProcessBll : CmsProcessTemplate
    {
        //public static IndexServiceInfo GetXmlIndexServiceInfo(string SiteId)
        //{
        //    IndexServiceInfo OIndexServiceInfo = new IndexServiceInfo();
        //    SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
        //    OIndexServiceInfo.IndexPath = WebConfig.GetConfigFromXml(OSiteParam, "IndexPath");
        //    OIndexServiceInfo.whatToIndex = WebConfig.GetConfigFromXml(OSiteParam, "whatToIndex");

        //    return OIndexServiceInfo;
        //}

        //public static IndexServiceInfo GetDocumentIndexServiceInfo(string SiteId)
        //{
        //    IndexServiceInfo OIndexServiceInfo = new IndexServiceInfo();
        //    SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
        //    OIndexServiceInfo.IndexPath = WebConfig.GetConfigFromXml(OSiteParam, "IndexPathDocument");
        //    OIndexServiceInfo.whatToIndex = WebConfig.GetConfigFromXml(OSiteParam, "whatToIndexDocument");

        //    return OIndexServiceInfo;
        //}
        public override string ServiceId
        {
            get
            {
                return "CmsBussinessProcessId";
            }
        }


        public override void ChangePassword(
            string SiteId,
            string AssetCode,
            string LoginName,
            string OldPassword,
            string NewPassword,
            string ReNewPassword)
        {
            if (!WebSessionUtility.GetCurrentLoginUser().Password.Equals(OldPassword))
            {
                throw new Exception("Mật khẩu cũ không hợp lệ!");
            }
            if (!NewPassword.Equals(ReNewPassword))
            {
                throw new Exception("Mật khẩu nhập lại không hợp lệ!");
            }
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.ExecuteNonQuery(null, " Update TableCmsAccount set AssetCode=@AssetCode, Password=@Password where LoginName=@LoginName",
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("LoginName", LoginName),
                        new DbParam("Password", NewPassword),
                    });
            WebSessionUtility.GetCurrentLoginUser().Password = NewPassword;
        }

        public override DataTypeCls CreateDataTypeModel(string SiteId, string DataTypeId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, " select * from TableDataType " +
                                               "     where DataTypeId=@DataTypeId",
                    new DbParam[] 
                    { 
                        new DbParam("DataTypeId", DataTypeId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            DataTypeCls ODataType = DataTypeParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return ODataType;
        }

        public override CmsDataCls CreateCmsDataModel(IDbTransaction Trans, string SiteId, string CmsDataId)
        {
            return CreateCmsDataModel(Trans, SiteId, CmsDataId, false, false);
        }


        public override DataSaveHistoryCls CreateCmsDataHistoryModel(IDbTransaction Trans, string SiteId, string CmsDataId, string HistoryDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(Trans, " SELECT * \r\n" +
                              " FROM [TableDataSaveHistory]  \r\n" +
                              " where DataId = @CmsDataId \r\n" +
                              " AND DataSaveHistoryId = @HistoryDataId ",
                    new DbParam[] 
                    { 
                        new DbParam("CmsDataId", CmsDataId),
                        new DbParam("HistoryDataId", HistoryDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            DataSaveHistoryCls OCmsData = DataSaveHistoryParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);

            dsResult.Clear();
            dsResult.Dispose();
            return OCmsData;
        }

        public override CmsDataCls CreateCmsDataModel(IDbTransaction Trans, string SiteId, string CmsDataId, bool IncPreview, bool IncDownload)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            return CreateCmsDataModel(Trans, SiteId, CmsDataId, IncPreview, IncDownload, OSiteParam.ConnectionString);
        }


        public override CmsDataCls CreateCmsDataModel(IDbTransaction Trans, string SiteId, string CmsDataId, bool IncPreview, bool IncDownload, string ConnectionString)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId, ConnectionString);
            string Query = "";
            if (IncPreview)
            {
                Query =
                    " Update TableData set TotalPreview=0 where TotalPreview is null;" +
                    " Update TableData set TotalPreview=TotalPreview+1 where DataId=@DataId; ";
            }
            if (IncDownload)
            {
                Query =
                    " Update TableData set TotalDownload=0 where TotalDownload is null;" +
                    " Update TableData set TotalDownload=TotalDownload+1 where DataId=@DataId; ";
            }
            DataSet dsResult =
                    DBService.GetDataSet(Trans, Query +
                                               " select TableData.*,GroupDataAlias=Alias, DataType=frkDataTypeId,DocTypeName,DocFieldName, DocSignerName,DocReleaseFromName from TableData " +
                                               "     left outer join TableDocType on DocTypeId=frkDocTypeId" +
                                               "     left outer join TableDocField on DocFieldId=frkDocFieldId" +
                                               "     left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
                                               "     left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId" +
                                               "     join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
                                               " where DataId=@DataId or DataAlias=@DataId",
                    new DbParam[] 
                    { 
                        new DbParam("DataId", CmsDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            CmsDataCls OCmsData = CmsDataParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return OCmsData;
        }



        public override GroupDataCls CreateGroupDataModel(IDbTransaction Trans, string SiteId, string GroupDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(Trans, "select TableGroupData.*,DataTypeName,AllowSub,AllowHtmlBody from TableGroupData " +
                                               "        join TableDataType on TableDataType.DataTypeId=frkDataTypeId" +
                                               "     where (GroupDataId=@GroupDataId or Alias=@GroupDataId)",
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            GroupDataCls OGroupData = GroupDataParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);

            dsResult.Clear();
            dsResult.Dispose();
            return OGroupData;
        }

        public override DataTypeCls[] ReadingDataType(string SiteId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableDataType where [Active]=@Active order by SortIndexDataType ",
                    new DbParam[] 
                    { 
                        new DbParam("Active", 1),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new DataTypeCls[0];
            }
            DataTypeCls[] DataType = DataTypeParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return DataType;
        }

        public override DataTypeCls[] ReadingDataTypeForRelation(string SiteId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableDataType where AllowRelation=@AllowRelation order by SortIndexDataType ",
                   new DbParam[] 
                    { 
                        new DbParam("AllowRelation", 1),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new DataTypeCls[0];
            }
            DataTypeCls[] DataType = DataTypeParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return DataType;
        }

        public override GroupDataCls[] ReadingGroupData(string SiteId, string DataTypeId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableGroupData " +
                                               "     where AssetCode=@AssetCode and DataLanguage=@DataLanguage and  frkDataTypeId=@DataTypeId order by EntryDate DESC",
                    new DbParam[] 
                    { 
                        new DbParam("DataTypeId", DataTypeId),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupData = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupData;
        }


        public override GroupDataCls[] ReadingGroupDataForPermission(string SiteId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableGroupData " +
                                               "        join TableDataType on TableDataType.DataTypeId=frkDataTypeId" +
                                               "     where [Active]=1 and AssetCode=@AssetCode and DataLanguage=@DataLanguage " +
                                               " order by frkDataTypeId,EntryDate DESC",
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupData = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupData;
        }


        public override GroupDataCls[] ReadingGroupData(string SiteId, string DataTypeId, string AssetCode)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableGroupData " +
                                               "     where AssetCode=@AssetCode and frkDataTypeId=@DataTypeId order by EntryDate DESC",
                    new DbParam[] 
                    { 
                        new DbParam("DataTypeId", DataTypeId),
                        new DbParam("AssetCode", AssetCode),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupData = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupData;
        }

        public override void AddGroupData(string SiteId, string DataTypeId, string Alias, string LinkDataAlias, string Subject, string Description)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string GroupDataId = System.Guid.NewGuid().ToString();
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            DBService.Insert(null, "TableGroupData",
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("frkDataTypeId", DataTypeId),
                        new DbParam("Alias", Alias),
                        new DbParam("LinkDataAlias", LinkDataAlias),
                        new DbParam("GroupDataName", Subject),
                        new DbParam("GroupDataDescription", Description),
                        new DbParam("EntryDate", System.DateTime.Now),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                    });
        }

        public override void SaveGroupData(string SiteId, string DataTypeId, string GroupDataId, string Alias, string LinkDataAlias, string Subject, string Description)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Update(null, "TableGroupData", "GroupDataId", GroupDataId,
                    new DbParam[] 
                    { 
                        new DbParam("Alias", Alias),
                        new DbParam("LinkDataAlias", LinkDataAlias),
                        new DbParam("GroupDataName", Subject),
                        new DbParam("GroupDataDescription", Description),
                    });
        }


        public override void DeleteGroupData(string SiteId, string GroupDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Delete from TableRelationData where frkSrcDataId in (select DataId from TableData where frkGroupDataId=@GroupDataId); " +
                " Delete from TableRelationData where frkRelDataId in (select DataId from TableData where frkGroupDataId=@GroupDataId); " +
                " Delete from TableData where frkGroupDataId=@GroupDataId; " +

                " Delete from TableDocReleaseFrom where frkGroupDataId=@GroupDataId; " +
                " Delete from TableDocSigner where frkGroupDataId=@GroupDataId; " +
                " Delete from TableDocType where frkGroupDataId=@GroupDataId; " +
                " Delete from TableDocField where frkGroupDataId=@GroupDataId; " +
                " Delete from TableDocYearRange where frkGroupDataId=@GroupDataId; " +
                " Delete from TableGroupData where GroupDataId=@GroupDataId; ";
            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
        }


        public override void SaveXml(
            IDbTransaction Trans,
            string SiteId,
            string AssetCode,
            string GroupDataId,
            DateTime EntryDate,
            string DataId)
        {
            GroupDataCls OGroupData = CreateGroupDataModel(Trans, SiteId, GroupDataId);
            if (OGroupData == null) return;
            if (!OGroupData.frkDataTypeId.Equals("document")) return;
            CmsDataCls OCmsData = CreateCmsDataModel(Trans, SiteId, DataId);
            DataSet dsXml = new DataSet();
            dsXml.ReadXml(new StringReader(OCmsData.GetXmlForCatche()));

            string SavePath = GetSaveDir(SiteId, OCmsData.EntryDate, WebSessionUtility.GetCurrentLoginUser().AssetCode, GroupDataId);
            string XmlSaveFile = SavePath + "\\" + DataId + ".xml";
            if (System.IO.File.Exists(XmlSaveFile))
            {
                try
                {
                    System.IO.File.Delete(XmlSaveFile);
                }
                catch { }
            }
            dsXml.WriteXml(XmlSaveFile);

            //doan nay update vao
            string UpdateQuery = "Update TableData set ArchiveXmlFile=@ArchiveXmlFile where DataId=@DataId";
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.ExecuteNonQuery(Trans, UpdateQuery, new DbParam[]{
                new DbParam("DataId",DataId),
                new DbParam("ArchiveXmlFile",XmlSaveFile),
            });

            //index
            string[] StoredFields = new string[]{
                            "DataAlias",
                            "DataSort",
                            "Subject",
                            "Description",
                            "EntryDate",
                            "UpdatedDate",
                            "frkDocTypeId",
                            "DocTypeName",
                            "frkDocFieldId",
                            "DocFieldName",
                            "frkDocReleaseFromId",
                            "DocReleaseFromName",
                            "frkDocSignerId",
                            "DocSignerName",
                            "SignDate",
                            "SearchSignDate",
                            "ReleaseDate",
                            "SearchReleaseDate",
                            "EffectedDate",
                            "SearchEffectedDate",
                            "frkGroupDataFolderId"
            };

            IndexServiceBll.Execute(GetXmlIndexServiceInfo(SiteId), StoredFields, false);
            IndexServiceBll.Execute(GetDocumentIndexServiceInfo(SiteId), null, false);
        }


        public override string AddCmsData(
            IDbTransaction Trans,
            string SiteId,
            string WorkflowDefId,
            string DataLanguage,
            string DataId,
            CmsDataCls OCmsData,
            CmsVoteAnswerItemCls[] CmsVoteAnswerItems,
            bool blnSaveXml)
        {
            string CmsDataId = null;
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);

            bool HasTrans = Trans != null;
            if (HasTrans == false)
            {
                Trans = DBService.BeginTransaction();
            }
            try
            {
                CmsDataId = AddCmsData(Trans, SiteId, WorkflowDefId, DataLanguage, DataId, OCmsData, blnSaveXml);
                //doan nay insert vao sub
                for (int iIndex = 0; iIndex < CmsVoteAnswerItems.Length; iIndex++)
                {
                    if (!string.IsNullOrEmpty(CmsVoteAnswerItems[iIndex].Subject.Trim()))
                    {
                        OCmsData.DataId = System.Guid.NewGuid().ToString();
                        if (!string.IsNullOrEmpty(CmsVoteAnswerItems[iIndex].Id))
                        {
                            OCmsData.DataId = CmsVoteAnswerItems[iIndex].Id;
                        }
                        OCmsData.Subject = CmsVoteAnswerItems[iIndex].Subject;
                        OCmsData.Description = "";
                        OCmsData.DataAlias = OCmsData.DataId.Substring(0, 8);
                        OCmsData.ParentDataId = CmsDataId;
                        OCmsData.SortIndex = CmsVoteAnswerItems[iIndex].SortIndex;
                        AddCmsData(Trans, SiteId, null, DataLanguage, OCmsData.DataId, OCmsData, false);
                    }
                }
                if (HasTrans == false)
                {
                    Trans.Commit();
                }
            }
            catch (Exception ex)
            {
                if (HasTrans == false)
                {
                    Trans.Rollback();
                }
                throw (ex);

            }
            return CmsDataId;
        }

        public override string AddCmsData(
                IDbTransaction Trans,
                string SiteId,
                string WorkflowDefId,
                string DataLanguage,
                string DataId,
                CmsDataCls OCmsData,
                bool blnSaveXml)
        {
            //doan nay doc danh sach map categor


            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string GroupDataId = OCmsData.frkGroupDataId;
            string UploadFile = OCmsData.UploadFile;
            string Alias = OCmsData.DataAlias;
            string ReleaseDate = OCmsData.ReleaseDate;
            string EffectedDate = OCmsData.EffectedDate;
            string EndEffectedDate = OCmsData.EndEffectedDate;
            string SignDate = OCmsData.SignDate;
            string ExpiredDate = OCmsData.ExpiredDate;
            string ParentDataId = OCmsData.ParentDataId;
            string Subject = OCmsData.Subject;
            string OtherSubject = OCmsData.OtherSubject;
            string Description = OCmsData.Description;
            string Body = OCmsData.Body;
            string Url = OCmsData.Url;
            string Source = OCmsData.Source;
            string Target = OCmsData.Target;
            int SortIndex = OCmsData.SortIndex;
            string DocStatus = OCmsData.DocStatus;
            string DocType = OCmsData.frkDocTypeId;
            string DocField = OCmsData.frkDocFieldId;
            string DocSigner = OCmsData.frkDocSignerId;
            string DocReleaseFrom = OCmsData.frkDocReleaseFromId;

            string ReplaceDoc = OCmsData.ReplaceDoc;
            string ModifyDoc = OCmsData.ModifyDoc;
            string VoteType = OCmsData.VoteType;
            int IsNew = OCmsData.IsNew;
            int AttachedSearchable = OCmsData.AttachedSearchable;
            string SubDataType = OCmsData.SubDataType;

            string Categories = OCmsData.Categories;
            string CategoryIds = OCmsData.CategoryIds;
            string HotCategoryIds = OCmsData.HotCategoryIds;
            string NewsTypeId = OCmsData.NewsTypeId;
            string ImageLevelId = OCmsData.ImageLevelId;
            string EventId = OCmsData.EventId;
            int ExpImageCount = OCmsData.ExpImageCount;
            string ExpImageLevelId = OCmsData.ExpImageLevelId;
            string NewsLevelId = OCmsData.NewsLevelId;
            int IsFocus = OCmsData.IsFocus;
            int IsShowAuthor = OCmsData.IsShowAuthor;
            int IsAdv = OCmsData.IsAdv;
            string Keyword = OCmsData.Keyword;
            string SurveyCode = OCmsData.SurveyCode;
            string Note = OCmsData.Note;
            string GroupDataFolderId = OCmsData.frkGroupDataFolderId;
            if (string.IsNullOrEmpty(GroupDataFolderId)) GroupDataFolderId = null;

            DateTime dReleaseDate = new System.DateTime();
            if (!string.IsNullOrEmpty(ReleaseDate))
            {
                dReleaseDate = FunctionUtilities.VNDateToDate(ReleaseDate);
            }

            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            object oReleaseDate = null;
            if (dReleaseDate != new System.DateTime())
            {
                //chck trung ngay....!
                oReleaseDate = dReleaseDate.ToString("yyyy/MM/dd");
                string Query = " select DataId from TableData where ReleaseDate=@ReleaseDate and DataAlias=@DataAlias";
                DataTable dtResult = DBService.GetDataTable(Trans, Query, new DbParam[]{
                    new DbParam("ReleaseDate",oReleaseDate),
                    new DbParam("DataAlias",Alias),
                });
                if (dtResult.Rows.Count > 0)
                {
                    throw new Exception("Đã có số văn bản theo ngày ban hành này rồi! Xin vui lòng kiểm tra lại!");
                }
            }


            DateTime dEffectedDate = new System.DateTime();
            if (!string.IsNullOrEmpty(EffectedDate))
            {
                dEffectedDate = FunctionUtilities.VNDateToDate(EffectedDate);
            }
            DateTime dEndEffectedDate = new System.DateTime();
            if (!string.IsNullOrEmpty(EndEffectedDate))
            {
                dEndEffectedDate = FunctionUtilities.VNDateToDate(EndEffectedDate);
            }
            DateTime dSignDate = new System.DateTime();
            if (!string.IsNullOrEmpty(SignDate))
            {
                dSignDate = FunctionUtilities.VNDateToDate(SignDate);
            }

            DateTime dExpiredDate = new System.DateTime();
            if (!string.IsNullOrEmpty(ExpiredDate))
            {
                dExpiredDate = FunctionUtilities.VNDateToDate(ExpiredDate);
            }


            GroupDataCls OGroupData = CreateGroupDataModel(null, SiteId, GroupDataId);


            string MapQuery = "select GroupDataCategoryId,MapId from TableGroupDataCategory where frkDataLanguageId=@DataLanguageId";
            DataTable dtMap = DBService.GetDataTable(Trans, MapQuery, new DbParam[]{
                new DbParam("DataLanguageId",DataLanguage)
            });

            if (OCmsData.SortIndex.Equals("0"))
            {
                //tu dong lay sortIndex
                //string Query = "select DataId from TableData where frkGroupDataId='" + GroupDataId + "' ";
                //if (!string.IsNullOrEmpty(OCmsData.ParentDataId))
                //{
                //    Query += " and ParentDataId='" + OCmsData.ParentDataId + "' ";
                //}

                string Query = "select DataId from TableData where frkGroupDataId=@frkGroupDataId ";
                if (!string.IsNullOrEmpty(OCmsData.ParentDataId))
                {
                    //Query += " and ParentDataId='" + OCmsData.ParentDataId + "' ";
                    Query += " and ParentDataId=@ParentDataId ";
                }

                DataTable dtCheck = DBService.GetDataTable(Trans, Query, new DbParam[]{
                                                            new DbParam("frkGroupDataId",GroupDataId),
                                                            new DbParam("ParentDataId",ParentDataId)});
                OCmsData.SortIndex = int.Parse((dtCheck.Rows.Count + 1).ToString());
            }

            string SaveUploadFile = "";
            if (!string.IsNullOrEmpty(OCmsData.UploadFile))
            {
                SaveUploadFile = new System.IO.FileInfo(UploadFile).Name;
            }

            if (Alias == null) Alias = "";
            Alias = Alias.Trim();
            Alias = Alias.Replace(" ", "");

            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            if (string.IsNullOrEmpty(DataLanguage))
            {
                DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            }
            if (string.IsNullOrEmpty(DataId))
            {
                DataId = System.Guid.NewGuid().ToString();
            }
            if (string.IsNullOrEmpty(ParentDataId)) ParentDataId = null;

            object oSignDate = null;

            object oEffectedDate = null;
            object oEndEffectedDate = null;
            if (dSignDate != new System.DateTime())
            {
                oSignDate = dSignDate.ToString("yyyy/MM/dd"); ;
            }

            if (dEffectedDate != new System.DateTime())
            {
                oEffectedDate = dEffectedDate.ToString("yyyy/MM/dd"); ;
            }
            if (dEndEffectedDate != new System.DateTime())
            {
                oEndEffectedDate = dEndEffectedDate.ToString("yyyy/MM/dd"); ;
            }

            string Avatar = "";
            string AttachDoc = "";
            string ArchiveDocFile = "";
            if (OGroupData.frkDataTypeId.Equals("document"))
            {
                AttachDoc = SaveUploadFile;
                ArchiveDocFile = SaveUploadFile;
            }
            else
            {
                Avatar = SaveUploadFile;
                ArchiveDocFile = SaveUploadFile;
            }
            DateTime CurrentTime = System.DateTime.Now;

            object oExpiredDate = null;
            if (dExpiredDate != new System.DateTime())
            {
                oExpiredDate = dExpiredDate;
            }

            bool HasTrans = Trans != null;
            if (HasTrans == false)
            {
                Trans = DBService.BeginTransaction();
            }
            try
            {
                DBService.Insert(Trans, "TableData",
                        new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                        new DbParam("frkGroupDataId", GroupDataId),
                        new DbParam("ParentDataId", ParentDataId),
                        new DbParam("DataAlias", Alias),
                        new DbParam("Subject",  Subject),
                        new DbParam("OtherSubject", OtherSubject),
                        new DbParam("Description", Description),
                        new DbParam("Body", Body),
                        new DbParam("Source", Source),
                        new DbParam("Url", Url),
                        new DbParam("Target", Target),
                        new DbParam("Avatar", Avatar),
                        new DbParam("AttachDoc", AttachDoc),
                        new DbParam("ArchiveDocFile", ArchiveDocFile),
                        new DbParam("EntryDate", CurrentTime.ToString("yyyy/MM/dd")),
                        new DbParam("UpdatedDate", CurrentTime.ToString("yyyy/MM/dd")),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                        new DbParam("SortIndex", SortIndex),
                        new DbParam("frkDocTypeId", string.IsNullOrEmpty(DocType)?null:DocType),
                        new DbParam("frkDocFieldId", string.IsNullOrEmpty(DocField)?null:DocField),
                        new DbParam("frkDocReleaseFromId", string.IsNullOrEmpty(DocReleaseFrom)?null:DocReleaseFrom),
                        new DbParam("frkDocSignerId", string.IsNullOrEmpty(DocSigner)?null:DocSigner),
                        new DbParam("DocStatus", DocStatus),
                        new DbParam("SignDate", oSignDate),
                        new DbParam("ReleaseDate", oReleaseDate),
                        new DbParam("EffectedDate", oEffectedDate),
                        new DbParam("EndEffectedDate", oEndEffectedDate),
                        new DbParam("ReplaceDoc", ReplaceDoc),
                        new DbParam("ModifyDoc", ModifyDoc),
                        new DbParam("VoteType", VoteType),
                        new DbParam("IsNew", IsNew),
                        new DbParam("AttachedSearchable", AttachedSearchable),
                        new DbParam("SubDataType", SubDataType),
                        new DbParam("frkGroupDataFolderId", GroupDataFolderId),
                        
                        //dành cho báo
                        new DbParam("Categories",Categories),
                        new DbParam("CategoryIds",CategoryIds),
                        new DbParam("HotCategoryIds",HotCategoryIds),

                        new DbParam("MapCategoryIds",string.Empty),
                        new DbParam("MapHotCategoryIds",string.Empty),

                        new DbParam("NewsTypeId",NewsTypeId),
                        new DbParam("ImageLevelId",ImageLevelId),
                        new DbParam("EventId",EventId),
                        new DbParam("ExpImageCount",ExpImageCount),
                        new DbParam("ExpImageLevelId",ExpImageLevelId),
                        new DbParam("NewsLevelId",NewsLevelId),
                        new DbParam("IsFocus",IsFocus),
                        new DbParam("IsShowAuthor",IsShowAuthor),
                        new DbParam("IsAdv",IsAdv),
                        new DbParam("Keyword",Keyword),
                        new DbParam("SurveyCode",SurveyCode),
                        new DbParam("Note",Note),
                        new DbParam("ExpiredDate",oExpiredDate),

                        new DbParam("WorkflowDefId",WorkflowDefId),

                        new DbParam("EntryBy",WebSessionUtility.GetCurrentLoginUser().LoginName),
                    });

                if (!string.IsNullOrEmpty(GroupDataFolderId))
                {
                    string DataBelongGroupDataFolderId = System.Guid.NewGuid().ToString();
                    DBService.Insert(Trans, "TableDataBelongGroupDataFolder",
                       new DbParam[] 
                    { 
                        new DbParam("DataBelongGroupDataFolderId", DataBelongGroupDataFolderId),
                        new DbParam("frkGroupDataFolderId", GroupDataFolderId),
                        new DbParam("frkDataId", DataId),
                    });
                }

                //cho nay update category
                string[] ItemCategories = CategoryIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int iIndex = 0; iIndex < ItemCategories.Length; iIndex++)
                {
                    string DataCategoryId = System.Guid.NewGuid().ToString();
                    DBService.Insert(Trans, "TableDataCategory", new DbParam[]{
                        new DbParam("DataCategoryId",DataCategoryId),
                        new DbParam("frkDataId",DataId),
                        new DbParam("frkGroupDataCategoryId",ItemCategories[iIndex]),
                    });
                }
                if (HasTrans == false)
                {
                    Trans.Commit();
                }
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                    WebSessionUtility.GetCurrentLoginUser().AssetCode,
                    "Document", "Thêm mới văn bản mã " + Alias + " với tiêu đề " + Subject,
                    WebSessionUtility.GetCurrentLoginUser().UserId,
                    WebSessionUtility.GetCurrentLoginUser().LoginName,
                    WebSessionUtility.GetCurrentLoginUser().FullName);


                //Save to History
                string SaveHistory =
                    " Insert into TableDataSaveHistory(" +
                    "       DataSaveHistoryId, DataId, Subject, OtherSubject, Description, Body, Source, UpdatedDate, Avatar, Url, Target, EntryBy, IsPublic, frkGroupDataId, DataAlias, AssetCode, DataLanguage, ParentDataId, frkDocTypeId, frkDocReleaseFromId, frkDocSignerId, frkDocFieldId, EffectedDate, ExpiredDate, SignDate, ReleaseDate, ReplaceDoc, ModifyDoc, DocStatus, AttachDoc, VoteType, frkDocYearRangeId, EndEffectedDate, AttachedSearchable, frkGroupDataFolderId, SubDataType, CategoryIds, HotCategoryIds, MapCategoryIds, MapHotCategoryIds, NewsTypeId, ImageLevelId, EventId, ExpImageCount, ExpImageLevelId, NewsLevelId, IsFocus, IsShowAuthor, IsAdv, Keyword, SurveyCode, Note, WorkflowDefId, Categories, SaveDate, SaveById, SaveByFullName, SaveRoleId, SaveRoleName, EntryDate" +
                    "   )" +
                    " (" +
                    "       select newid(),DataId, N'" + Subject + "', OtherSubject,N'" + Description + "', Body, Source, UpdatedDate, Avatar, Url, Target, EntryBy, IsPublic, frkGroupDataId, DataAlias, AssetCode, DataLanguage, ParentDataId, '" + OCmsData.frkDocTypeId + "', '" + OCmsData.frkDocReleaseFromId + "', '" + OCmsData.frkDocSignerId + "', frkDocFieldId, '" + oEffectedDate + "','" + oExpiredDate + "', '" + oSignDate + "','" + oReleaseDate + "', ReplaceDoc, ModifyDoc,'" + OCmsData.DocStatus + "', '" + OCmsData.AttachDoc + "', VoteType, frkDocYearRangeId, '" + oEndEffectedDate + "', " + OCmsData.AttachedSearchable + ", frkGroupDataFolderId, SubDataType, CategoryIds, HotCategoryIds, MapCategoryIds, MapHotCategoryIds, NewsTypeId, ImageLevelId, EventId, ExpImageCount, ExpImageLevelId, NewsLevelId, IsFocus, IsShowAuthor, IsAdv, Keyword, SurveyCode, Note, WorkflowDefId, Categories,GetDate(),@SaveById, @SaveByFullName, @SaveRoleId,@SaveRoleName,EntryDate from TableData" +
                    "           where DataId=@DataId" +
                    " )";

                DBService.ExecuteNonQuery(Trans, SaveHistory,
                       new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                        new DbParam("SaveById",WebSessionUtility.GetCurrentLoginUser().UserId),
                        new DbParam("SaveByFullName",WebSessionUtility.GetCurrentLoginUser().FullName),

                        new DbParam("SaveRoleId",WebSessionUtility.GetCurrentLoginUser().RoleId),
                        new DbParam("SaveRoleName",WebSessionUtility.GetCurrentLoginUser().RoleName),
                    });

            }
            catch (Exception ex)
            {
                if (HasTrans == false)
                {
                    Trans.Rollback();
                }
                throw (ex);
            }

            if (blnSaveXml)
            {
                SaveXml(Trans, SiteId, AssetCode, GroupDataId, CurrentTime, DataId);
            }
            return DataId;
        }

        public override void SaveCmsData(
              IDbTransaction Trans,
              string SiteId,
              string DataId,
              CmsDataCls OCmsData,
              CmsVoteAnswerItemCls[] CmsVoteAnswerItems,
              bool blnSaveXml
          )
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);

            bool HasTrans = Trans != null;
            if (HasTrans == false)
            {
                Trans = DBService.BeginTransaction();
            }
            try
            {
                SaveCmsData(Trans, SiteId, DataId, OCmsData, blnSaveXml);
                string ParentDataId = OCmsData.DataId;
                string Query = " Delete from TableData where ParentDataId=@ParentDataId";
                DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
                    new DbParam("ParentDataId",OCmsData.DataId)
                });
                //doan nay insert vao sub
                for (int iIndex = 0; iIndex < CmsVoteAnswerItems.Length; iIndex++)
                {
                    if (!string.IsNullOrEmpty(CmsVoteAnswerItems[iIndex].Subject.Trim()))
                    {
                        OCmsData.DataId = System.Guid.NewGuid().ToString();
                        if (!string.IsNullOrEmpty(CmsVoteAnswerItems[iIndex].Id))
                        {
                            OCmsData.DataId = CmsVoteAnswerItems[iIndex].Id;
                        }
                        OCmsData.Subject = CmsVoteAnswerItems[iIndex].Subject;
                        OCmsData.Description = "";
                        OCmsData.DataAlias = OCmsData.DataId.Substring(0, 8);
                        OCmsData.ParentDataId = ParentDataId;
                        OCmsData.SortIndex = CmsVoteAnswerItems[iIndex].SortIndex;
                        AddCmsData(Trans, SiteId, null, OCmsData.DataLanguage, OCmsData.DataId, OCmsData, false);
                    }
                }
                if (HasTrans == false)
                {
                    Trans.Commit();
                }
            }
            catch (Exception ex)
            {
                if (HasTrans == false)
                {
                    Trans.Rollback();
                }
            }
        }

        public override void SaveCmsData(
            IDbTransaction Trans,
            string SiteId,
            string DataId,
            CmsDataCls OCmsData,
            bool blnSaveXml)
        {
            string Alias = OCmsData.DataAlias;
            string Subject = OCmsData.Subject;
            string OtherSubject = OCmsData.OtherSubject;
            string Description = OCmsData.Description;
            string Body = OCmsData.Body;
            string Source = OCmsData.Source;
            string Url = OCmsData.Url;
            string Target = OCmsData.Target;
            string SortIndex = OCmsData.SortIndex.ToString();
            string DocType = OCmsData.frkDocTypeId;
            string DocField = OCmsData.frkDocFieldId;
            string DocReleaseFrom = OCmsData.frkDocReleaseFromId;
            string DocSigner = OCmsData.frkDocSignerId;
            string DocStatus = OCmsData.DocStatus;
            string ReleaseDate = OCmsData.ReleaseDate;
            string EffectedDate = OCmsData.EffectedDate;
            string EndEffectedDate = OCmsData.EndEffectedDate;
            string SignDate = OCmsData.SignDate;
            string ExpiredDate = OCmsData.ExpiredDate;

            string GroupDataFolderId = OCmsData.frkGroupDataFolderId;
            if (string.IsNullOrEmpty(GroupDataFolderId)) GroupDataFolderId = null;

            DateTime dReleaseDate = new System.DateTime();
            if (!string.IsNullOrEmpty(ReleaseDate))
            {
                dReleaseDate = FunctionUtilities.VNDateToDate(ReleaseDate);
            }

            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            object oReleaseDate = null;
            if (dReleaseDate != new System.DateTime())
            {
                oReleaseDate = dReleaseDate.ToString("yyyy/MM/dd");
                //chck trung ngay....!
                string Query = " select DataId from TableData where ReleaseDate=@ReleaseDate and DataAlias=@DataAlias and DataId<>@DataId";
                DataTable dtResult = DBService.GetDataTable(Trans, Query, new DbParam[]{
                    new DbParam("ReleaseDate",oReleaseDate),
                    new DbParam("DataAlias",Alias),
                    new DbParam("DataId",DataId),
                });
                if (dtResult.Rows.Count > 0)
                {
                    throw new Exception("Đã có số văn bản theo ngày ban hành này rồi! Xin vui lòng kiểm tra lại!");
                }
            }


            DateTime dEffectedDate = new System.DateTime();
            if (!string.IsNullOrEmpty(EffectedDate))
            {
                dEffectedDate = FunctionUtilities.VNDateToDate(EffectedDate);
            }

            DateTime dEndEffectedDate = new System.DateTime();
            if (!string.IsNullOrEmpty(EndEffectedDate))
            {
                dEndEffectedDate = FunctionUtilities.VNDateToDate(EndEffectedDate);
            }
            DateTime dSignDate = new System.DateTime();
            if (!string.IsNullOrEmpty(SignDate))
            {
                dSignDate = FunctionUtilities.VNDateToDate(SignDate);
            }

            DateTime dExpiredDate = new System.DateTime();
            if (!string.IsNullOrEmpty(ExpiredDate))
            {
                dExpiredDate = FunctionUtilities.VNDateToDate(ExpiredDate);
            }

            string ReplaceDoc = OCmsData.ReplaceDoc;
            string ModifyDoc = OCmsData.ModifyDoc;
            string VoteType = OCmsData.VoteType;
            int IsNew = OCmsData.IsNew;
            int AttachedSearchable = OCmsData.AttachedSearchable;

            //dành cho báo
            string CategoryIds = OCmsData.CategoryIds;
            string HotCategoryIds = OCmsData.HotCategoryIds;
            string NewsTypeId = OCmsData.NewsTypeId;
            string ImageLevelId = OCmsData.ImageLevelId;
            string EventId = OCmsData.EventId;
            string ExpImageCount = OCmsData.ExpImageCount.ToString();
            string ExpImageLevelId = OCmsData.ExpImageLevelId;
            string NewsLevelId = OCmsData.NewsLevelId;
            string IsFocus = OCmsData.IsFocus.ToString();
            string IsShowAuthor = OCmsData.IsShowAuthor.ToString();
            string IsAdv = OCmsData.IsAdv.ToString();
            string Keyword = OCmsData.Keyword;
            string SurveyCode = OCmsData.SurveyCode;
            string Note = OCmsData.Note;


            if (Alias == null) Alias = "";
            Alias = Alias.Trim();
            Alias = Alias.Replace(" ", "");

            string MapQuery = "select GroupDataCategoryId,MapId from TableGroupDataCategory where frkDataLanguageId=@DataLanguageId";
            DataTable dtMap = DBService.GetDataTable(Trans, MapQuery, new DbParam[]{
                new DbParam("DataLanguageId",OCmsData.DataLanguage)
            });

            bool HasTrans = Trans != null;
            if (HasTrans == false)
            {
                Trans = DBService.BeginTransaction();
            }
            try
            {
                if (string.IsNullOrEmpty(Alias)) Alias = System.Guid.NewGuid().ToString().Substring(0, 8);
                object oSignDate = null;

                object oEffectedDate = null;
                object oEndEffectedDate = null;
                object oExpiredDate = null;

                if (dExpiredDate != new System.DateTime())
                {
                    oExpiredDate = dExpiredDate.ToString("yyyy/MM/dd");
                }

                if (dSignDate != new System.DateTime())
                {
                    oSignDate = dSignDate.ToString("yyyy/MM/dd");
                }

                if (dEffectedDate != new System.DateTime())
                {
                    oEffectedDate = dEffectedDate.ToString("yyyy/MM/dd");
                }

                if (dEndEffectedDate != new System.DateTime())
                {
                    oEndEffectedDate = dEndEffectedDate.ToString("yyyy/MM/dd");
                }

                string SaveUploadFile = "";
                if (!string.IsNullOrEmpty(OCmsData.UploadFile))
                {
                    SaveUploadFile = new System.IO.FileInfo(OCmsData.UploadFile).Name;
                }

                string AttachDoc = "";
                string ArchiveDocFile = "";
                AttachDoc = SaveUploadFile;
                ArchiveDocFile = SaveUploadFile;

                DBService.Update(Trans, "TableData", "DataId", DataId,
                        new DbParam[] 
                    { 
                        new DbParam("DataAlias", Alias),
                        new DbParam("Subject", Subject),
                        new DbParam("OtherSubject", OtherSubject),
                        new DbParam("Description", Description),
                        new DbParam("Body", Body),
                        new DbParam("Source", Source),
                        new DbParam("Url", Url),
                        new DbParam("Target", Target),
                        new DbParam("UpdatedDate", System.DateTime.Now,DbType.DateTime),
                        new DbParam("SortIndex", SortIndex),
                        new DbParam("frkDocTypeId", string.IsNullOrEmpty(DocType)?null:DocType),
                        new DbParam("frkDocFieldId", string.IsNullOrEmpty(DocField)?null:DocField),
                        new DbParam("frkDocReleaseFromId", string.IsNullOrEmpty(DocReleaseFrom)?null:DocReleaseFrom),
                        new DbParam("frkDocSignerId", string.IsNullOrEmpty(DocSigner)?null:DocSigner),
                        new DbParam("DocStatus", DocStatus),
                        new DbParam("SignDate", oSignDate),
                        new DbParam("ReleaseDate", oReleaseDate),
                        new DbParam("EffectedDate", oEffectedDate),
                        new DbParam("EndEffectedDate", oEndEffectedDate),
                        new DbParam("ReplaceDoc", ReplaceDoc),
                        new DbParam("ModifyDoc", ModifyDoc),
                        new DbParam("VoteType", VoteType),
                        new DbParam("IsNew", IsNew),
                        new DbParam("AttachedSearchable", AttachedSearchable),

                        new DbParam("frkGroupDataFolderId", GroupDataFolderId),

                        //dành cho báo
                        new DbParam("CategoryIds",CategoryIds),
                        new DbParam("HotCategoryIds",HotCategoryIds),

                        new DbParam("MapCategoryIds",string.Empty),
                        new DbParam("MapHotCategoryIds",string.Empty),
                        new DbParam("NewsTypeId",NewsTypeId),
                        new DbParam("ImageLevelId",ImageLevelId),
                        new DbParam("EventId",EventId),
                        new DbParam("ExpImageCount",ExpImageCount),
                        new DbParam("ExpImageLevelId",ExpImageLevelId),
                        new DbParam("NewsLevelId",NewsLevelId),
                        new DbParam("IsFocus",IsFocus),
                        new DbParam("IsShowAuthor",IsShowAuthor),
                        new DbParam("IsAdv",IsAdv),
                        new DbParam("Keyword",Keyword),
                        new DbParam("SurveyCode",SurveyCode),
                        new DbParam("Note",Note),
                        new DbParam("ExpiredDate",oExpiredDate),
                         new DbParam("AttachDoc", AttachDoc),
                        new DbParam("ArchiveDocFile", ArchiveDocFile),

                    });

                DBService.ExecuteNonQuery(Trans, "Delete TableDataBelongGroupDataFolder where frkGroupDataFolderId=@GroupDataFolderId",
                    new DbParam[] 
                        { 
                            new DbParam("GroupDataFolderId", GroupDataFolderId),
                        });
                if (!string.IsNullOrEmpty(GroupDataFolderId))
                {
                    string DataBelongGroupDataFolderId = System.Guid.NewGuid().ToString();
                    DBService.Insert(Trans, "TableDataBelongGroupDataFolder",
                       new DbParam[] 
                        { 
                            new DbParam("DataBelongGroupDataFolderId", DataBelongGroupDataFolderId),
                            new DbParam("frkGroupDataFolderId", GroupDataFolderId),
                            new DbParam("frkDataId", DataId),
                        });
                }

                ///Save to history
                string SaveHistory =
                    " Insert into TableDataSaveHistory(" +
                    "       DataSaveHistoryId, DataId, Subject, OtherSubject, Description, Body, Source, UpdatedDate, Avatar, Url, Target, EntryBy, IsPublic, frkGroupDataId, DataAlias, AssetCode, DataLanguage, ParentDataId, frkDocTypeId, frkDocReleaseFromId, frkDocSignerId, frkDocFieldId, EffectedDate, ExpiredDate, SignDate, ReleaseDate, ReplaceDoc, ModifyDoc, DocStatus, AttachDoc, VoteType, frkDocYearRangeId, EndEffectedDate, AttachedSearchable, frkGroupDataFolderId, SubDataType, CategoryIds, HotCategoryIds, MapCategoryIds, MapHotCategoryIds, NewsTypeId, ImageLevelId, EventId, ExpImageCount, ExpImageLevelId, NewsLevelId, IsFocus, IsShowAuthor, IsAdv, Keyword, SurveyCode, Note, WorkflowDefId, Categories, SaveDate, SaveById, SaveByFullName, SaveRoleId, SaveRoleName" +
                    "   )" +
                    " (" +
                    "       select newid(),DataId, N'" + Subject + "', OtherSubject,N'" + Description + "', Body, Source, UpdatedDate, Avatar, Url, Target, EntryBy, IsPublic, frkGroupDataId, DataAlias, AssetCode, DataLanguage, ParentDataId, '" + OCmsData.frkDocTypeId + "', '" + OCmsData.frkDocReleaseFromId + "', '" + OCmsData.frkDocSignerId + "', frkDocFieldId, '" + oEffectedDate + "','" + oExpiredDate + "', '" + oSignDate + "','" + oReleaseDate + "', ReplaceDoc, ModifyDoc,'" + OCmsData.DocStatus + "', '" + OCmsData.AttachDoc + "', VoteType, frkDocYearRangeId, '" + oEndEffectedDate + "', " + OCmsData.AttachedSearchable + ", frkGroupDataFolderId, SubDataType, CategoryIds, HotCategoryIds, MapCategoryIds, MapHotCategoryIds, NewsTypeId, ImageLevelId, EventId, ExpImageCount, ExpImageLevelId, NewsLevelId, IsFocus, IsShowAuthor, IsAdv, Keyword, SurveyCode, Note, WorkflowDefId, Categories,GetDate(),@SaveById, @SaveByFullName, @SaveRoleId,@SaveRoleName from TableData" +
                    "           where DataId=@DataId" +
                    " )";

                DBService.ExecuteNonQuery(Trans, SaveHistory,
                       new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                        new DbParam("SaveById",WebSessionUtility.GetCurrentLoginUser().UserId),
                        new DbParam("SaveByFullName",WebSessionUtility.GetCurrentLoginUser().FullName),

                        new DbParam("SaveRoleId",WebSessionUtility.GetCurrentLoginUser().RoleId),
                        new DbParam("SaveRoleName",WebSessionUtility.GetCurrentLoginUser().RoleName),
                    });


                //cho nay update category
                DBService.ExecuteNonQuery(Trans, "Delete from TableDataCategory where frkDataId=@DataId", new DbParam[]{
                    new DbParam("DataId",OCmsData.DataId)
                });
                string[] ItemCategories = CategoryIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int iIndex = 0; iIndex < ItemCategories.Length; iIndex++)
                {
                    string DataCategoryId = System.Guid.NewGuid().ToString();
                    DBService.Insert(Trans, "TableDataCategory", new DbParam[]{
                        new DbParam("DataCategoryId",DataCategoryId),
                        new DbParam("frkDataId",OCmsData.DataId),
                        new DbParam("frkGroupDataCategoryId",ItemCategories[iIndex]),
                    });
                }

                DBService.ExecuteNonQuery(Trans, " Update TableWorkflowAction set Subject=@Subject where RecordId=@DataId", new DbParam[]{
                    new DbParam("DataId",OCmsData.DataId),
                    new DbParam("Subject",OCmsData.Subject),
                });

                DBService.ExecuteNonQuery(Trans, " Update TableWorkflowActionHistory set Subject=@Subject where RecordId=@DataId", new DbParam[]{
                    new DbParam("DataId",OCmsData.DataId),
                    new DbParam("Subject",OCmsData.Subject),
                });

                //doan nay save vao history....!
                //bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, OCmsData.DataId);

                if (HasTrans == false)
                {
                    Trans.Commit();
                }
            }
            catch (Exception ex)
            {
                if (HasTrans == false)
                {
                    Trans.Rollback();
                }
                throw (ex);
            }
            if (blnSaveXml)
            {
                SaveXml(null, SiteId, OCmsData.AssetCode, OCmsData.frkGroupDataId, OCmsData.EntryDate, DataId);
            }

            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Cập nhật văn bản mã " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);

        }


        public override void DeleteCmsData(string SiteId, string DataId)
        {
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, DataId);
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Delete from TableRelationData where frkSrcDataId=@DataId or frkRelDataId=@DataId; " +
                " Delete from TableDocumentAttached where DataId=@DataId; " +
                " Delete from TableDocumentArchive where frkDataId=@DataId; " +
                " Delete from TableDataCategory where frkDataId=@DataId; " +
                " Delete from TableWorkflowAction where RecordId=@DataId;" +
                " Delete from TableWorkflowActionHistory where RecordId=@DataId;" +
                " Delete from TableWorkflowHasReceived where RecordId=@DataId;" +
                " Delete from TableWorkflowHasSent where RecordId=@DataId;" +
                " Delete from TableWorkflowPermissionGrant where ObjectId=@DataId;" +
                " Delete from TableWorkflowCurrentProcess where RecordId=@DataId;" +
                " Delete from TableDataBelongGroupDataFolder where frkDataId=@DataId;" +
                " Delete from TableData where ParentDataId=@DataId; " +
                " Delete from TableData where DataId=@DataId; ";
            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                    });

            if (OCmsData != null)
            {
                DateTime CurrentTime = OCmsData.EntryDate;
                string SavePath = GetSaveDir(SiteId, CurrentTime, WebSessionUtility.GetCurrentLoginUser().AssetCode, OCmsData.frkGroupDataId);
                try
                {
                    System.IO.File.Delete(OCmsData.GetAvatarFilePath(SiteId, WebConfig.DataPathRoot(OSiteParam)));
                }
                catch { }


                string XmlSaveFile = SavePath + "\\" + DataId + ".xml";
                try
                {
                    System.IO.File.Delete(XmlSaveFile);
                }
                catch { }

                //xoa archive file
                try
                {
                    System.IO.File.Delete(OCmsData.GetAttachDocFile(SiteId, WebConfig.DataPathRoot(OSiteParam)));
                }
                catch { }
                try
                {
                    System.IO.File.Delete(OCmsData.GetAttachDocFileXml(SiteId, WebConfig.DataPathRoot(OSiteParam)));
                }
                catch { }
            }
            else
            {
                string DataPathRoot = WebConfig.DataPathRoot(OSiteParam);
                string ArchiveDocFile = OCmsData.ArchiveDocFile;
                int iFound = ArchiveDocFile.IndexOf("DocumentArchives");
                if (iFound != -1)
                {
                    ArchiveDocFile = ArchiveDocFile.Substring(iFound);
                    ArchiveDocFile = DataPathRoot + "\\" + ArchiveDocFile;
                }

                System.IO.File.Delete(ArchiveDocFile);


                string ArchiveXmlFile = OCmsData.ArchiveXmlFile;
                iFound = ArchiveDocFile.IndexOf("DocumentArchives");
                if (iFound != -1)
                {
                    ArchiveXmlFile = ArchiveXmlFile.Substring(iFound);
                    ArchiveXmlFile = DataPathRoot + "\\" + ArchiveXmlFile;
                }

                System.IO.File.Delete(ArchiveXmlFile);
            }
            string[] StoredFields = new string[]{
                            "DataAlias",
                            "DataSort",
                            "Subject",
                            "Description",
                            "EntryDate",
                            "UpdatedDate",
                            "frkDocTypeId",
                            "DocTypeName",
                            "frkDocFieldId",
                            "DocFieldName",
                            "frkDocReleaseFromId",
                            "DocReleaseFromName",
                            "frkDocSignerId",
                            "DocSignerName",
                            "SignDate",
                            "SearchSignDate",
                            "ReleaseDate",
                            "SearchReleaseDate",
                            "EffectedDate",
                            "SearchEffectedDate"
            };

            IndexServiceBll.Execute(GetXmlIndexServiceInfo(SiteId), StoredFields, false);
            IndexServiceBll.Execute(GetDocumentIndexServiceInfo(SiteId), null, false);
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Xóa văn bản mã " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }



        public override void ExecuteIndexService(string SiteId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string[] StoredFields = new string[]{
                            "DataAlias",
                            "DataSort",
                            "Subject",
                            "Description",
                            "EntryDate",
                            "UpdatedDate",
                            "frkDocTypeId",
                            "DocTypeName",
                            "frkDocFieldId",
                            "DocFieldName",
                            "frkDocReleaseFromId",
                            "DocReleaseFromName",
                            "frkDocSignerId",
                            "DocSignerName",
                            "SignDate",
                            "SearchSignDate",
                            "ReleaseDate",
                            "SearchReleaseDate",
                            "EffectedDate",
                            "SearchEffectedDate"
            };

            IndexServiceBll.Execute(GetXmlIndexServiceInfo(SiteId), StoredFields, false);
            IndexServiceBll.Execute(GetDocumentIndexServiceInfo(SiteId), null, false);
        }

        public override void ChangeAvatarFile(string SiteId, string DataId, string AvatarFile)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            if (!string.IsNullOrEmpty(AvatarFile))
            {
                AvatarFile = new System.IO.FileInfo(AvatarFile).Name;
            }
            string Query =
                " Update TableData set Avatar=@Avatar where DataId=@DataId; ";

            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                        new DbParam("Avatar", AvatarFile),
                    });
        }

        public override void ChangeAttachDocFile(string SiteId, string DataId, string AttachDocFile)
        {
            int iFoundError = AttachDocFile.IndexOf("ERROR:");
            if (iFoundError != -1)
            {
                AttachDocFile = AttachDocFile.Substring(iFoundError);
                throw new Exception(AttachDocFile);
            }
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, DataId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string ShortAttachDocFile = "";
            if (!string.IsNullOrEmpty(AttachDocFile))
            {
                ShortAttachDocFile = new System.IO.FileInfo(AttachDocFile).Name;
            }
            string Query =
                " Update TableData set AttachDoc=@AttachDoc,ArchiveDocFile=@ArchiveDocFile where DataId=@DataId; " +
                " Update TableDocumentArchive set NeedIndexDocumentAttached=1,AttachDoc=@AttachDoc,DocumentContent=@DocumentContent where frkDataId=@DataId; ";

            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                        new DbParam("AttachDoc", ShortAttachDocFile),
                        new DbParam("ArchiveDocFile", AttachDocFile),
                        new DbParam("DocumentContent", FunctionUtilities.GetBytesFromFile(AttachDocFile),DbType.Binary),
                    });
            SaveXml(null, SiteId, OCmsData.AssetCode, OCmsData.frkGroupDataId, OCmsData.EntryDate, DataId);
        }

        public override void PublicData(IDbTransaction Trans, string SiteId, string DataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            CmsDataCls OCmsData = CreateCmsDataModel(Trans, SiteId, DataId);
            string Query =
                " Update TableData set IsPublic=1,DocStatus=1 where DataId=@DataId";

            DBService.ExecuteNonQuery(Trans, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                    });
            SaveXml(Trans, SiteId, OCmsData.AssetCode, OCmsData.frkGroupDataId, OCmsData.EntryDate, DataId);
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Phát hành lên website " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }

        public override void UnPublicData(IDbTransaction Trans, string SiteId, string DataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            CmsDataCls OCmsData = CreateCmsDataModel(Trans, SiteId, DataId);
            string Query =
                " Update TableData set IsPublic=0,DocStatus=0 where DataId=@DataId";

            DBService.ExecuteNonQuery(Trans, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                    });
            SaveXml(Trans, SiteId, OCmsData.AssetCode, OCmsData.frkGroupDataId, OCmsData.EntryDate, DataId);
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Ngưng phát hành trên website " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }



        public override void PublicGroupData(string SiteId, string GroupDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Update TableGroupData set ActiveGroupData=1 where GroupDataId=@GroupDataId";

            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
        }

        public override void UnPublicGroupData(string SiteId, string GroupDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Update TableGroupData set ActiveGroupData=0 where GroupDataId=@GroupDataId";

            DBService.ExecuteNonQuery(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
        }


        public override CmsDataCls[] ReadingCmsData(string SiteId, string GroupDataId, string ParentDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName from TableData " +
                "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
                "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
                "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
                "       left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId" +
                "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
                "     where  TableData.frkGroupDataId=@GroupDataId ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId='" + ParentDataId + "' ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }



        public string GetCmsDataIdByDocNumber(string SiteId, string Subject)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select * from TableData where  TableData.Subject=@Subject ";

            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("Subject", Subject),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return string.Empty;
            }
            CmsDataCls CmsDatas = CmsDataParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas.DataId;
        }

        public override CmsDataCls[] ReadingCmsDataForDataType(
            string SiteId,
            string DataType)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName from TableData " +
                "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
                "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
                "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
                "       left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId" +
                "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
                "     where IsPublic=1 and frkDataTypeId=@DataType";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataType", DataType),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }


        //public static CmsDataCls[] ReadingCmsDataForFolder(string SiteId, string GroupDataId, string GroupDataFolderId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName from TableData " +
        //        "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
        //        "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
        //        "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
        //        "       left outer join TableDocReleaseFrom on DocReleaseFromId=frkDocReleaseFromId" +
        //        "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
        //        "     where  TableData.frkGroupDataId=@GroupDataId ";
        //    if (!string.IsNullOrEmpty(GroupDataFolderId))
        //    {
        //        Query += " and DataId in (select frkDataId from TableDataBelongGroupDataFolder where frkGroupDataFolderId='" + GroupDataFolderId + "')";
        //    }
        //    else
        //    {
        //        Query += " and 1=2 ";
        //    }
        //    Query +=
        //        " order by SortIndex";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("GroupDataId", GroupDataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new CmsDataCls[0];
        //    }
        //    CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return CmsDatas;
        //}

        //public static CmsDataCls[] ReadingCmsDataForPublicFolder(string SiteId, string GroupDataId, string PublicGroupDataFolderId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName from TableData " +
        //        "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
        //        "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
        //        "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
        //        "       left outer join TableDocReleaseFrom on DocReleaseFromId=frkDocReleaseFromId" +
        //        "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
        //        "     where  TableData.frkGroupDataId=@GroupDataId ";
        //    if (!string.IsNullOrEmpty(PublicGroupDataFolderId))
        //    {
        //        Query += " and DataId in (select frkDataId from TableDataBelongPublicGroupDataFolder where frkPublicGroupDataFolderId='" + PublicGroupDataFolderId + "')";
        //    }
        //    else
        //    {
        //        Query += " and 1=2 ";
        //    }
        //    Query +=
        //        " order by SortIndex";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("GroupDataId", GroupDataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new CmsDataCls[0];
        //    }
        //    CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return CmsDatas;
        //}

        //public static CmsDataCls[] ReadingCmsDataForFolderForAddPublicFolder(string SiteId, string GroupDataId, string GroupDataFolderId,string Folder)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName from TableData " +
        //        "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
        //        "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
        //        "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
        //        "       left outer join TableDocReleaseFrom on DocReleaseFromId=frkDocReleaseFromId" +
        //        "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
        //        "     where  TableData.frkGroupDataId=@GroupDataId and DataId not in (select frkDataId from TableDataBelongPublicGroupDataFolder where frkPublicGroupDataFolderId='" + Folder + "')";
        //    if (!string.IsNullOrEmpty(GroupDataFolderId))
        //    {
        //        Query += " and DataId in (select frkDataId from TableDataBelongGroupDataFolder where frkGroupDataFolderId='" + GroupDataFolderId + "')";
        //    }
        //    else
        //    {
        //        Query += " and 1=2 ";
        //    }
        //    Query +=
        //        " order by SortIndex";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("GroupDataId", GroupDataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new CmsDataCls[0];
        //    }
        //    CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return CmsDatas;
        //}

        //public static GroupDataFolderCls[] ReadingCmsDataFolderForData(string SiteId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "   select GroupDataFolderId,FolderName,Description,ParentGroupDataFolderId=frkParentGroupDataFolderId,SortIndex,GroupDataId=frkGroupDataId from TableDataBelongGroupDataFolder " +
        //        "       join TableGroupDataFolder on GroupDataFolderId=frkGroupDataFolderId" +
        //        "   where frkDataId=@DataId order by SortIndex";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("DataId", DataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new GroupDataFolderCls[0];
        //    }
        //    GroupDataFolderCls[] GroupDataFolders = GroupDataFolderParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return GroupDataFolders;
        //}

        //public static PublicGroupDataFolderCls[] ReadingCmsDataPublicFolder(string SiteId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "   select PublicGroupDataFolderId,FolderName,Description,ParentPublicGroupDataFolderId=frkParentPublicGroupDataFolderId,SortIndex,GroupDataId=frkGroupDataId from TableDataBelongPublicGroupDataFolder " +
        //        "       join TablePublicGroupDataFolder on PublicGroupDataFolderId=frkPublicGroupDataFolderId" +
        //        "   where frkDataId=@DataId order by SortIndex";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("DataId", DataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new PublicGroupDataFolderCls[0];
        //    }
        //    PublicGroupDataFolderCls[] PublicGroupDataFolders = PublicGroupDataFolderParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return PublicGroupDataFolders;
        //}

        public override CmsDataCls[] ReadingCmsDataForVote(string SiteId, string GroupDataId, string ParentDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId,DocTypeName,DocFieldName, DocReleaseFromName,DocSignerName,TotalVoteChecked=(select count(StudentSurveyItemId) from TableStudentSurveyItem join TableStudentSurvey on tableStudentSurvey.StudentSurveyId=frkStudentSurveyId where frkSurveyId=@GroupDataId and frkStudentSurveyId=StudentSurveyId and SurveyDataChecked=1 and SurveyDataId=DataId) from TableData " +
                "       left outer join TableDocType on DocTypeId=frkDocTypeId" +
                "       left outer join TableDocField on DocFieldId=frkDocFieldId" +
                "       left outer join TableDocSigner on DocSignerId=frkDocSignerId" +
                "       left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId" +
                "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
                "     where  TableData.frkGroupDataId=@GroupDataId ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId='" + ParentDataId + "' ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }


        public override GroupDataCls[] ReadingGroupDataForSurvey(string SiteId, string AssetCode)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select * from TableGroupData where ActiveGroupData=1 and frkDataTypeId='vote' ";
            if (!string.IsNullOrEmpty(AssetCode))
            {
                Query += " and AssetCode='" + AssetCode + "' ";
            }
            DataSet dsResult =
                    DBService.GetDataSet(null, Query, null);
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupDatas = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupDatas;
        }



        public override CmsDataCls[] ReadingCmsDataForVoteDetail(
            string SiteId,
            string GroupDataId,
            string ParentDataId,
            string StudentSurveyId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId," +
                " TotalVoteChecked=(select count(StudentSurveyItemId) from TableStudentSurveyItem " +
                "       join TableStudentSurvey on TableStudentSurvey.StudentSurveyId=frkStudentSurveyId " +
                "       where frkSurveyId=@GroupDataId and frkStudentSurveyId=StudentSurveyId " +
                "           and SurveyDataChecked=1 and SurveyDataId=DataId and StudentSurveyId=@StudentSurveyId " +
                "   ), " +
                " SurveyDataText=(select TOP 1 IsNull(SurveyDataText,'') from TableStudentSurveyItem " +
                "       join TableStudentSurvey on TableStudentSurvey.StudentSurveyId=frkStudentSurveyId " +
                "       where frkSurveyId=@GroupDataId and frkStudentSurveyId=StudentSurveyId " +
                "           and SurveyDataId=DataId and StudentSurveyId=@StudentSurveyId " +
                "   ) " +
                " from TableData " +
                "       left outer join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId" +
                "     where  TableData.frkGroupDataId=@GroupDataId ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId='" + ParentDataId + "' ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("StudentSurveyId", StudentSurveyId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }



        public override CmsDataCls ReadingCmsDataForVoteDetailText(
            string SiteId,
            string GroupDataId,
            string ParentDataId,
            string StudentSurveyId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " select TOP 1 VoteDataText=IsNull(SurveyDataText,'') from TableStudentSurveyItem " +
                "       join TableStudentSurvey on TableStudentSurvey.StudentSurveyId=frkStudentSurveyId " +
                "  where frkSurveyId=@GroupDataId and frkStudentSurveyId=StudentSurveyId " +
                "       and SurveyDataId=@SurveyDataId and StudentSurveyId=@StudentSurveyId ";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("StudentSurveyId", StudentSurveyId),
                        new DbParam("SurveyDataId", ParentDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            CmsDataCls OCmsData = CmsDataParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return OCmsData;
        }


        public override CmsDataCls[] ReadingCmsDataIsPublic(string SiteId, string GroupDataId, string ParentDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId from TableData " +
                                               "     join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId " +
                                               "     where  (frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) and IsPublic=@IsPublic ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId=@ParentDataId ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("IsPublic", 1),
                        new DbParam("ParentDataId", ParentDataId),
                        
                        
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }


        //public override CmsDataCls[] ReadingCmsDataIsPublicByUser(
        //    string SiteId, 
        //    string GroupDataId, 
        //    string ParentDataId, 
        //    string EntryBy, 
        //    string isPublic, 
        //    string sortValue)
        public override CmsDataCls[] ReadingCmsDataIsPublicByUser(
            string SiteId,
            string GroupDataId,
            string ParentDataId,
            string EntryBy,
            string isPublic,
            string sortValue,
            string releasefrom,
            string docfield,
            string doctype,
            string docsigner,
            string docNo)
        {
            try
            {
                IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
                string Query =

                    "select TableData.*,GroupDataAlias=Alias, DataType=frkDataTypeId,DocTypeName,DocFieldName, DocSignerName,DocReleaseFromName  " +
                    "    from TableData    " +
                    "    left outer join TableDocType on DocTypeId=frkDocTypeId   " +
                    "    left outer join TableDocField on DocFieldId=frkDocFieldId   " +
                    "    left outer join TableDocSigner on DocSignerId=frkDocSignerId   " +
                    "    left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId   " +
                    "    join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId    " +
                    //select TableData.*,DataType=frkDataTypeId from TableData " +
                    //                                   "        join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId" +
                    //                                   "     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) and IsPublic=1 AND ReleaseDate < '" + DateTime.Now.AddMonths(7) + "'";
                    //"     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) and IsPublic=1 AND ReleaseDate < '" + DateTime.Now.AddMonths(7).ToString("yyyy/MM/dd") + "'";
                "     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) AND ReleaseDate < '" + DateTime.Now.AddMonths(7).ToString("yyyy/MM/dd") + "'";

                if (!string.IsNullOrEmpty(EntryBy))
                {
                    Query += " and EntryBy='" + EntryBy + "' ";
                }
                if (!isPublic.Equals("2") && !string.IsNullOrEmpty(isPublic))
                {
                    //Query += " and IsPublic=" + isPublic + " ";
                    Query += " and DocStatus=" + isPublic + " ";

                }

                //docno
                if (!string.IsNullOrEmpty(docNo))
                {
                    Query += " and Subject='" + docNo + "' ";
                }

                if (!string.IsNullOrEmpty(releasefrom))
                {
                    Query += " and TableData.frkDocReleaseFromId='" + releasefrom + "' ";
                }
                if (!string.IsNullOrEmpty(docsigner))
                {
                    Query += " and TableData.frkDocSignerId='" + docsigner + "' ";
                }
                if (!string.IsNullOrEmpty(docfield))
                {
                    Query += " and TableData.frkDocFieldId='" + docfield + "' ";
                }
                if (!string.IsNullOrEmpty(doctype))
                {
                    Query += " and TableData.frkDocTypeId='" + doctype + "' ";
                }



                if (!string.IsNullOrEmpty(ParentDataId))
                {
                    Query += " and ParentDataId='" + ParentDataId + "' ";
                }
                else
                {
                    Query += " and ParentDataId is null ";
                }
                if ((sortValue.Trim().Length > 0 && !sortValue.Equals("ASC")) || sortValue.Trim().Length > 0 && !sortValue.Equals("DESC"))
                    Query +=
                        " order by " + sortValue;
                else
                    Query +=
                    " order by ReleaseDate DESC";
                DataSet dsResult =
                        DBService.GetDataSet(null, Query,
                        new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
                if (dsResult.Tables[0].Rows.Count == 0)
                {
                    return new CmsDataCls[0];
                }
                CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
                dsResult.Clear();
                dsResult.Dispose();
                return CmsDatas;
            }
            catch
            {
                return new CmsDataCls[0];
            }
        }

        public override CmsDataCls[] SearchAdvancePublicCmsData(
             string SiteId,
             string GroupDataId,
             string ParentDataId,
             string EntryBy, string isPublic, string sortValue,
             string documentno,
             string Subject,
             string sfd,
             string std,
             string rfd,
             string rtd,
             string efd,
             string etd,
             string releasefrom,
             string docfield,
             string doctype,
             string docsigner,
             string gdf,
             string status,
             string yrf,
             string yrt
            )
        {
            try
            {
                IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
                string Query =

                    "select TableData.*,GroupDataAlias=Alias, DataType=frkDataTypeId,DocTypeName,DocFieldName, DocSignerName,DocReleaseFromName  " +
                    "    from TableData    " +
                    "    left outer join TableDocType on DocTypeId=frkDocTypeId   " +
                    "    left outer join TableDocField on DocFieldId=frkDocFieldId   " +
                    "    left outer join TableDocSigner on DocSignerId=frkDocSignerId   " +
                    "    left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId   " +
                    "    join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId    " +
                    //"     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) AND ReleaseDate < '" + DateTime.Now.AddMonths(7).ToString("yyyy/MM/dd") + "'";
                    "     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) AND ReleaseDate < @ReleaseDate";

                //trang thai
                if (!isPublic.Equals("2") && !string.IsNullOrEmpty(isPublic))
                {
                    //Query += " and DocStatus=" + isPublic + " ";
                    Query += " and DocStatus=@isPublic";
                }
                //Co quan ban hanh
                if (!string.IsNullOrEmpty(releasefrom))
                {
                    //Query += " and TableData.frkDocReleaseFromId='" + releasefrom + "' ";
                    Query += " and TableData.frkDocReleaseFromId=@releasefrom";
                }
                // Nguoi ky
                if (!string.IsNullOrEmpty(docsigner))
                {
                    //Query += " and TableData.frkDocSignerId='" + docsigner + "' ";
                    Query += " and TableData.frkDocSignerId=@docsigner";
                }
                // Linh vuc van ban
                if (!string.IsNullOrEmpty(docfield))
                {
                    //Query += " and TableData.frkDocFieldId='" + docfield + "' ";
                    Query += " and TableData.frkDocFieldId=@docfield";
                }
                //Loai van ban
                if (!string.IsNullOrEmpty(doctype))
                {
                    //Query += " and TableData.frkDocTypeId='" + doctype + "' ";
                    Query += " and TableData.frkDocTypeId=@doctype";
                }

                //so van ban
                if (!string.IsNullOrEmpty(documentno))
                {
                    //Query += " and TableData.subject='" + documentno + "' ";
                    Query += " and TableData.subject=@documentno";
                }
                //trich yeu...
                if (!string.IsNullOrEmpty(Subject))
                {
                    Query += " and TableData.Subject like N'%" + Subject + "%' OR TableData.Description like N'%" + Subject + "%' OR TableData.Body like N'%" + Subject + "%'";
                    //Query += " and TableData.Subject like N'%@Subject' OR TableData.Description like N'%@Subject' OR TableData.Body like N'%@Subject'";
                }

                ////Ngay ban hanh
                //if (!string.IsNullOrEmpty(rfd))
                //{
                //    //Query += " and ReleaseDate>='" + DateTime.Parse(rfd).ToString("yyyy/MM/dd")+ "' ";
                //    Query += " and ReleaseDate>=@ReleaseDate";
                //}

                //if (!string.IsNullOrEmpty(rtd))
                //{
                //    Query += " and ReleaseDate='" + DateTime.Parse(rtd).ToString("yyyy/MM/dd") + "' ";
                //    //Query += " and ReleaseDate<=@rtd";
                //}

                DateTime rfdDT = System.DateTime.Now;
                DateTime rtdDT = System.DateTime.Now;

                if (!string.IsNullOrEmpty(rfd) && !string.IsNullOrEmpty(rtd))
                {
                    Query += " and ReleaseDate BETWEEN @rfd and @rtd ";
                    rfdDT = DateTime.Parse(rfd);
                    rtdDT = DateTime.Parse(rtd);
                }


                //Ngay hieu luc
                //if (!string.IsNullOrEmpty(efd))
                //{
                //    //Query += " and EffectedDate>=@efd";
                //    Query += " and EffectedDate>='" + DateTime.Parse(efd).ToString("yyyy/MM/dd") + "'";
                //}

                //if (!string.IsNullOrEmpty(etd))
                //{
                //    //Query += " and EffectedDate<=@etd";
                //    Query += " and EffectedDate<='" + DateTime.Parse(etd).ToString("yyyy/MM/dd") + "'";
                //}      

                DateTime efdDT = System.DateTime.Now;
                DateTime etdDT = System.DateTime.Now;
                if (!string.IsNullOrEmpty(efd) && !string.IsNullOrEmpty(etd))
                {
                    Query += " and EffectedDate BETWEEN @efd and @etd ";

                    efdDT = DateTime.Parse(efd);
                    etdDT = DateTime.Parse(etd);
                }

                if (!string.IsNullOrEmpty(yrf) && !string.IsNullOrEmpty(yrt))
                {
                    if (yrt.Equals("0")) {
                        yrt = DateTime.Now.Year.ToString();
                    }
                    Query += " and year(ReleaseDate) BETWEEN @yrf and @yrt ";                    
                }

                if (!string.IsNullOrEmpty(ParentDataId))
                {
                    //Query += " and ParentDataId='" + ParentDataId + "'";
                    Query += " and ParentDataId=@ParentDataId ";
                }

                else
                {
                    Query += " and ParentDataId is null ";
                }

                if (sortValue.Trim().Length > 0)
                    Query +=
                        " order by " + sortValue;
                else
                    Query +=
                    " order by ReleaseDate DESC";
                DataSet dsResult =
                        DBService.GetDataSet(null, Query,
                        new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("ReleaseDate", DateTime.Now.AddMonths(7),DbType.DateTime),
                        new DbParam("isPublic", isPublic),
                        new DbParam("releasefrom", releasefrom),     
                        new DbParam("docsigner", docsigner),
                        new DbParam("docfield", docfield),
                        new DbParam("doctype", doctype),
                        new DbParam("documentno", documentno),
                        new DbParam("rfd", rfdDT,DbType.DateTime),
                        new DbParam("rtd", rtdDT,DbType.DateTime),
                        new DbParam("efd", efdDT,DbType.DateTime),
                        new DbParam("etd", etdDT,DbType.DateTime),                        
                        new DbParam("ParentDataId", ParentDataId),  
                        new DbParam("yrf", yrf),                        
                        new DbParam("yrt", yrt),                       
                    });

                if (dsResult.Tables[0].Rows.Count == 0)
                {
                    return new CmsDataCls[0];
                }

                CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
                dsResult.Clear();
                dsResult.Dispose();
                return CmsDatas;
            }
            catch (Exception ex)
            {
                throw ex;
                //return new CmsDataCls[0];
            }
        }

        public override CmsDataCls[] SearchAdvancePublicCmsData(
            string SiteId,
            string GroupDataId,
            string ParentDataId,
            string EntryBy,
            string isPublic,
            string sortValue,
            string documentno,
            string Subject,
            string sfd,
            string std,
            string rfd,
            string rtd,
            string efd,
            string etd,
            string releasefrom,
            string docfield,
            string doctype,
            string docsigner
            )
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =

                "select TableData.*,GroupDataAlias=Alias, DataType=frkDataTypeId,DocTypeName,DocFieldName, DocSignerName,DocReleaseFromName,JobTitle  " +
                "    from TableData    " +
                "    left outer join TableDocType on DocTypeId=frkDocTypeId   " +
                "    left outer join TableDocField on DocFieldId=frkDocFieldId   " +
                "    left outer join TableDocSigner on DocSignerId=frkDocSignerId   " +
                "    left outer join TableDocReleaseFrom on DocReleaseFromId=TableData.frkDocReleaseFromId   " +
                "    join TableGroupData on TableGroupData.GroupDataId=TableData.frkGroupDataId    " +
                "     where  (TableData.frkGroupDataId=@GroupDataId or TableGroupData.Alias=@GroupDataId) ";
            //Nguoi tao
            if (!string.IsNullOrEmpty(EntryBy))
            {
                //Query += " and EntryBy='" + EntryBy + "' ";
                Query += " and EntryBy=@EntryBy ";
            }
            //Trang thai van ban
            if (!isPublic.Equals("2") && !string.IsNullOrEmpty(isPublic))
            {
                //Query += " and DocStatus=" + isPublic + " ";
                Query += " and DocStatus=@DocStatus ";
            }
            //Don ban hanh
            if (!string.IsNullOrEmpty(releasefrom))
            {
                //Query += " and TableData.frkDocReleaseFromId='" + releasefrom + "' ";
                Query += " and TableData.frkDocReleaseFromId=@releasefrom ";
            }
            //Don vi ban hanh
            if (!string.IsNullOrEmpty(docsigner))
            {
                //Query += " and TableData.frkDocSignerId='" + docsigner + "' ";
                Query += " and TableData.frkDocSignerId=@docsigner ";
            }
            //Linh vuc
            if (!string.IsNullOrEmpty(docfield))
            {
                Query += " and TableData.frkDocFieldId=@docfield ";
            }
            //Loai van ban
            if (!string.IsNullOrEmpty(doctype))
            {
                Query += " and TableData.frkDocTypeId=@doctype ";
            }
            //so van ban
            if (!string.IsNullOrEmpty(documentno))
            {
                Query += " and TableData.Subject=@documentno ";
            }
            //Trich yeu...
            if (!string.IsNullOrEmpty(Subject))
            {
                Query += " and TableData.Subject like N'%" + Subject + "%' OR TableData.Description like N'%" + Subject + "%' OR TableData.Body like N'%" + Subject + "%'";
            }

            //Ngay ban hanh
            DateTime rfdDT = System.DateTime.Now;
            DateTime rtdDT = System.DateTime.Now;

            if (!string.IsNullOrEmpty(rfd) && !string.IsNullOrEmpty(rtd))
            {
                Query += " and ReleaseDate BETWEEN @rfd and @rtd ";
                rfdDT = DateTime.Parse(rfd);
                rtdDT = DateTime.Parse(rtd);
            }

            //Ngay hieu luc
            DateTime efdDT = System.DateTime.Now;
            DateTime etdDT = System.DateTime.Now;
            if (!string.IsNullOrEmpty(efd) && !string.IsNullOrEmpty(etd))
            {
                Query += " and EffectedDate BETWEEN @efd and @etd ";

                efdDT = DateTime.Parse(efd);
                etdDT = DateTime.Parse(etd);
            }

            ////Ngay het han
            //DateTime expfDT = System.DateTime.Now;
            //DateTime exptDT = System.DateTime.Now;

            //if (!string.IsNullOrEmpty(efd) && !string.IsNullOrEmpty(etd))
            //{
            //    Query += " and ExpiredDate BETWEEN @rfd and @rtd ";
            //    expfDT = DateTime.Parse(rfd);
            //    exptDT = DateTime.Parse(rtd);
            //}
            //if (!string.IsNullOrEmpty(efd))
            //{
            //    Query += " and ExpiredDate>='" + DateTime.Parse(efd).ToString("yyyy/MM/dd") + "' ";
            //}

            //if (!string.IsNullOrEmpty(etd))
            //{
            //    Query += " and ExpiredDate<='" + DateTime.Parse(etd).ToString("yyyy/MM/dd") + "' ";
            //}

            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId=@ParentDataId ";
            }

            else
            {
                Query += " and ParentDataId is null ";
            }
            if (sortValue.Trim().Length > 0)
                Query +=
                    " order by " + sortValue;
            else
                Query +=
                " order by ReleaseDate DESC";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                         new DbParam("EntryBy", EntryBy),
                         new DbParam("DocStatus", isPublic),
                         new DbParam("releasefrom", releasefrom),
                         new DbParam("docsigner", docsigner),
                         new DbParam("docfield", docfield),
                         new DbParam("doctype", doctype),
                         new DbParam("documentno", documentno),
                         new DbParam("rfd",rfdDT,DbType.DateTime),
                         new DbParam("rtd", rtdDT,DbType.DateTime),                       
                         new DbParam("efd",efdDT,DbType.DateTime),
                         new DbParam("etd", etdDT,DbType.DateTime),                         
                         new DbParam("ParentDataId", ParentDataId),                         
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }


        public override CmsDataCls[] ReadingTopCmsDataIsPublicSortByDate(string SiteId, string GroupDataId, string ParentDataId, string SortType, int Top)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TOP " + Top + " TableData.*,DataType=frkDataTypeId from TableData " +
                                               "        join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId" +
                                               "     where  frkGroupDataId=@GroupDataId and IsPublic=1 ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId='" + ParentDataId + "' ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by UpdatedDate " + SortType;
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }

        public override CmsDataCls[] ReadingCmsDataIsPublicSortByDate(string SiteId, string GroupDataId, string ParentDataId, string SortType)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableData.*,DataType=frkDataTypeId from TableData " +
                                               "        join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId" +
                                               "     where  frkGroupDataId=@GroupDataId and IsPublic=@IsPublic ";
            if (!string.IsNullOrEmpty(ParentDataId))
            {
                Query += " and ParentDataId=@ParentDataId ";
            }
            else
            {
                Query += " and ParentDataId is null ";
            }
            Query +=
                " order by UpdatedDate " + SortType;
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("ParentDataId", ParentDataId),
                        new DbParam("IsPublic", 1),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }

        public override CmsDataCls[] ReadingCmsDataIsPublicExclusive(string SiteId, string GroupDataId, string ExclusideId, int TOP)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string TOPText = "";
            if (TOP != 0)
            {
                TOPText = " TOP " + TOP + " ";
            }
            string Query =
                " select " + TOPText + " TableData.*,DataType=frkDataTypeId from TableData " +
                "        join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId" +
                "     where  frkGroupDataId=@GroupDataId and IsPublic=1 and DataId<>@DataId" +
                " order by EntryDate DESC";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataId", GroupDataId),
                        new DbParam("DataId", ExclusideId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }


        public override GroupDataCls[] ReadingGroupDataForInput(string SiteId, string DataType)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableGroupData.*,PlugInModuleId from TableGroupData " +
                "       join TableDataType on TableDataType.DataTypeId=frkDataTypeId" +
                "  where AssetCode=@AssetCode and DataLanguage=@DataLanguage and frkDataTypeId=@DataType";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                        new DbParam("DataType", DataType),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupDatas = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupDatas;
        }


        public override GroupDataCls[] ReadingGroupDataForInput(string SiteId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableGroupData.*,PlugInModuleId from TableGroupData " +
                "       join TableDataType on TableDataType.DataTypeId=frkDataTypeId" +
                "  where AssetCode=@AssetCode and DataLanguage=@DataLanguage";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupDatas = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupDatas;
        }

        public override CmsDataCls[] SearchCmsData(string SiteId, string DataTypeId, string Subject, string Description)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = "select * from TableData where 1=1 ";
            if (!string.IsNullOrEmpty(Subject))
            {
                Query += " and Subject like N'%" + Subject + "%' ";
            }
            if (!string.IsNullOrEmpty(Description))
            {
                Query += " and Description like N'%" + Description + "%' ";
            }
            Query += " order by UpdatedDate";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query, null);
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }

        public override CmsDataCls[] SearchCmsData(string SiteId, string DataTypeId, string Keyword)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = "select TableData.*,GroupDataAlias=TableGroupData.Alias, GroupDataName from TableData join TableGroupData on TableGroupData.GroupDataId=frkGroupDataId where TableData.IsPublic=1 and frkDataTypeId='" + DataTypeId + "' ";
            if (!string.IsNullOrEmpty(Keyword))
            {
                Query += " and Subject like N'%" + Keyword + "%' ";
            }
            Query += " order by UpdatedDate";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query, null);
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataCls[0];
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDatas;
        }

        public override void SendContactUs(
            string SiteId,
            string FromName,
            string FromEmail,
            string FromAddress,
            string FromPhone,
            string FromTitle,
            string SendContent)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string ContactUsId = System.Guid.NewGuid().ToString();
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);

            string AssetCode = WebConfig.GetConfigFromXml(OSiteParam, "DefaultAssetCode");
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Insert(null, "TableContactUs", new DbParam[]{
                new DbParam("ContactUsId",ContactUsId),
                new DbParam("FullName",FromName),
                new DbParam("Email",FromEmail),
                new DbParam("PhoneNumber",FromPhone),
                new DbParam("Address",FromAddress),
                new DbParam("Title",FromTitle),
                new DbParam("Body",SendContent),
                new DbParam("EntryDate",System.DateTime.Now),
                new DbParam("HasRead",0),
                new DbParam("AssetCode",AssetCode),
                new DbParam("DataLanguage",DataLanguage),
            });
        }


        public override GroupDataCls[] ReadingGroupDataForVote(string SiteId, string DataTypeId, string AssetCode, string StudentId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, " select * from TableGroupData " +
                                               "    where AssetCode=@AssetCode and frkDataTypeId=@DataTypeId " +
                                               "    and  GroupDataId not in (select frkSurveyId from TableStudentSurvey where frkStudentId=@StudentId) and [ActiveGroupData]=1 " +
                                               " order by EntryDate DESC",
                    new DbParam[] 
                    { 
                        new DbParam("DataTypeId", DataTypeId),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("StudentId", StudentId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataCls[0];
            }
            GroupDataCls[] GroupData = GroupDataParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return GroupData;
        }


        public override void AddDocumentRelation(string SiteId, string SrcDataId, string RelDataId, string RelationTypeId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, SrcDataId);
            string RelationDataId = System.Guid.NewGuid().ToString();
            DBService.Insert(null, "TableRelationData",
                    new DbParam[] 
                    { 
                        new DbParam("RelationDataId", RelationDataId),
                        new DbParam("frkSrcDataId", SrcDataId),
                        new DbParam("frkRelDataId", RelDataId),
                        new DbParam("frkRelationTypeId", RelationTypeId),
                    });
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Thêm mới văn bản liên quan vào văn bản " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }

        public override void AddDocumentRelationList(string SiteId, string SrcDataId, string[] RelDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);

            RelationTypeCls[] oRelationTypeClss = RelationTypeProcessBll.ReadingAllRelationType(SiteId);
            for (int iIndex = 0; iIndex < RelDataId.Length; iIndex++)
            {
                if (string.IsNullOrEmpty(RelDataId[iIndex]))
                    continue;

                string OCmsDataId = this.GetCmsDataIdByDocNumber(SiteId, RelDataId[iIndex]);

                string RelationDataId = System.Guid.NewGuid().ToString();
                DBService.Insert(null, "TableRelationData",
                        new DbParam[] 
                    { 
                        new DbParam("RelationDataId", RelationDataId),
                        new DbParam("frkSrcDataId", SrcDataId),
                        new DbParam("frkRelDataId", OCmsDataId),
                        new DbParam("frkRelationTypeId", oRelationTypeClss[iIndex].RelationTypeId ),
                    });
            }
        }

        public override void DeleteDocumentRelation(string SiteId, string RelationDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.ExecuteNonQuery(null, "Delete from TableRelationData where RelationDataId=@RelationDataId",
                    new DbParam[] 
                    { 
                        new DbParam("RelationDataId", RelationDataId),
                    });
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Xóa văn bản liên quan",
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }

        public override void DeleteDocument(string SiteId, string DataId)
        {
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, DataId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.ExecuteNonQuery(null,
                " Delete from TableDataBelongGroupDataFolder where frkDataId=@DataId; " +
                " Delete from TableData where DataId=@DataId; ",
                   new DbParam[] 
                    { 
                        new DbParam("DataId", DataId),
                    });
            SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddSysLogProcess(SiteId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                "Document", "Xóa văn bản số " + OCmsData.DataAlias + " tiêu đề " + OCmsData.Subject,
                WebSessionUtility.GetCurrentLoginUser().UserId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName);
        }

        //public static void RemoveDocumentFromFolder(string SiteId, string GroupDataFolderId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    DBService.ExecuteNonQuery(null, "Delete from TableDataBelongGroupDataFolder where frkGroupDataFolderId=@GroupDataFolderId and frkDataId=@DataId",
        //            new DbParam[] 
        //            { 
        //                new DbParam("GroupDataFolderId", GroupDataFolderId),
        //                new DbParam("DataId", DataId),
        //            });
        //}

        //public static void RemoveDocumentFromPublicFolder(string SiteId, string PublicGroupDataFolderId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    DBService.ExecuteNonQuery(null, "Delete from TableDataBelongPublicGroupDataFolder where frkPublicGroupDataFolderId=@PublicGroupDataFolderId and frkDataId=@DataId",
        //            new DbParam[] 
        //            { 
        //                new DbParam("PublicGroupDataFolderId ", PublicGroupDataFolderId ),
        //                new DbParam("DataId", DataId),
        //            });
        //}

        public override CmsDataRelationCls[] ReadingDocumentRelation(string SiteId, string SrcDataId, string RelationTypeId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                   DBService.GetDataSet(null, "     select TableRelationData.*,DataId,DataAlias,Subject,AttachDoc from TableRelationData " +
                                              "     join TableData on TableData.DataId=frkRelDataId" +
                                              "     where frkRelationTypeId=@RelationTypeId and frkSrcDataId=@SrcDataId" +
                                              "     order by EntryDate DESC",
                   new DbParam[] 
                    { 
                        new DbParam("RelationTypeId", RelationTypeId),
                        new DbParam("SrcDataId", SrcDataId),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataRelationCls[0];
            }
            CmsDataRelationCls[] CmsDataRelations = CmsDataRelationParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDataRelations;
        }



        public override CmsDataRelationCls[] ReadingDocumentRelationOut(string SiteId, string SrcDataId, string RelationTypeId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                   DBService.GetDataSet(null, "     select TableRelationData.*,DataId,DataAlias,Subject from TableRelationData " +
                                              "     join TableData on TableData.DataId=frkSrcDataId" +
                                              "     where frkRelationTypeId=@RelationTypeId and frkRelDataId=@SrcDataId" +
                                              "     order by EntryDate DESC",
                   new DbParam[] 
                    { 
                        new DbParam("RelationTypeId", RelationTypeId),
                        new DbParam("SrcDataId", SrcDataId),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new CmsDataRelationCls[0];
            }
            CmsDataRelationCls[] CmsDataRelations = CmsDataRelationParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsDataRelations;
        }


        //public static StudentSurveyCls[] ReadingVotedStudentList(string SiteId, string GroupDataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select StudentSurveyId,StudentId, LoginName,FullName,Course,Class,VoteDate from tableStudentSurvey" +
        //        "       join TableStudent on TableStudent.StudentId=frkStudentId" +
        //        "     where  frkSurveyId=@VoteId"+
        //        "        order by VoteDate";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,
        //            new DbParam[] 
        //            { 
        //                new DbParam("VoteId", GroupDataId),
        //            });
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new StudentSurveyCls[0];
        //    }
        //    StudentSurveyCls[] StudentSurveys = StudentSurveyParser.ParseFromDataTable(dsResult.Tables[0]);
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return StudentSurveys;
        //}




        //public static void AddDataToGroupDataFolder(
        //    string SiteId, 
        //    string[] CheckedIds,
        //    string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    IDbTransaction Trans = DBService.BeginTransaction();
        //    try
        //    {
        //        string Query = "Delete from [TableDataBelongGroupDataFolder] where frkDataId=@DataId";
        //        DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
        //            new DbParam("DataId",DataId)
        //        });
        //        for (int iIndex = 0; iIndex < CheckedIds.Length; iIndex++)
        //        {
        //            string DataBelongGroupDataFolderId = System.Guid.NewGuid().ToString();
        //            DBService.Insert(Trans, "TableDataBelongGroupDataFolder", 
        //                new DbParam[]{
        //                     new DbParam("DataBelongGroupDataFolderId",DataBelongGroupDataFolderId),
        //                     new DbParam("frkGroupDataFolderId",CheckedIds[iIndex]),
        //                     new DbParam("frkDataId",DataId),
        //                });
        //        }
        //        Trans.Commit();
        //    }
        //    catch (Exception ex)
        //    {
        //        Trans.Rollback();
        //        throw (ex);
        //    }
        //}



        //public static void MoveFolder(
        //    string SiteId,
        //    string FromFolderId,
        //    string ToFolderId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    IDbTransaction Trans = DBService.BeginTransaction();
        //    try
        //    {
        //        string Query = " Update TableGroupDataFolder set frkParentGroupDataFolderId='" + ToFolderId+"' where GroupDataFolderId='"+FromFolderId+"'";
        //        DBService.ExecuteNonQuery(Trans, Query, null);
        //        Trans.Commit();
        //    }
        //    catch (Exception ex)
        //    {
        //        Trans.Rollback();
        //        throw (ex);
        //    }
        //}


        //public static void AddDataToPublicGroupDataFolder(
        //    string SiteId,
        //    string[] CheckedIds,
        //    string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    IDbTransaction Trans = DBService.BeginTransaction();
        //    try
        //    {
        //        string Query = "Delete from [TableDataBelongPublicGroupDataFolder] where frkDataId=@DataId";
        //        DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
        //            new DbParam("DataId",DataId)
        //        });
        //        for (int iIndex = 0; iIndex < CheckedIds.Length; iIndex++)
        //        {
        //            string DataBelongGroupDataFolderId = System.Guid.NewGuid().ToString();
        //            DBService.Insert(Trans, "TableDataBelongPublicGroupDataFolder",
        //                new DbParam[]{
        //                     new DbParam("DataBelongGroupDataFolderId",DataBelongGroupDataFolderId),
        //                     new DbParam("frkPublicGroupDataFolderId",CheckedIds[iIndex]),
        //                     new DbParam("frkDataId",DataId),
        //                });
        //        }
        //        Trans.Commit();
        //    }
        //    catch (Exception ex)
        //    {
        //        Trans.Rollback();
        //        throw (ex);
        //    }
        //}


        //public static string[] ReadingDataInFolder(string SiteId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select frkGroupDataFolderId from TableDataBelongGroupDataFolder" +
        //        "     where  frkDataId='" + DataId + "'";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,null);
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new string[0];
        //    }
        //    string[] CheckedIds = new string[dsResult.Tables[0].Rows.Count];
        //    for (int iIndex = 0; iIndex < CheckedIds.Length; iIndex++)
        //    {
        //        CheckedIds[iIndex] = (string)dsResult.Tables[0].Rows[iIndex]["frkGroupDataFolderId"];
        //    }
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return CheckedIds;
        //}

        //public static string[] ReadingDataInPublicFolder(string SiteId, string DataId)
        //{
        //    IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
        //    string Query =
        //        "select frkPublicGroupDataFolderId from TableDataBelongPublicGroupDataFolder" +
        //        "     where  frkDataId='" + DataId + "'";
        //    DataSet dsResult =
        //            DBService.GetDataSet(null, Query,null);
        //    if (dsResult.Tables[0].Rows.Count == 0)
        //    {
        //        return new string[0];
        //    }
        //    string[] CheckedIds = new string[dsResult.Tables[0].Rows.Count];
        //    for (int iIndex = 0; iIndex < CheckedIds.Length; iIndex++)
        //    {
        //        CheckedIds[iIndex] = (string)dsResult.Tables[0].Rows[iIndex]["frkPublicGroupDataFolderId"];
        //    }
        //    dsResult.Clear();
        //    dsResult.Dispose();
        //    return CheckedIds;
        //}




        public override Collection<CmsDataCls> GetDocumentRelation(string SiteId, string DataId, Collection<CmsDataCls> ResCmsData)
        {
            if (ResCmsData == null) ResCmsData = new Collection<CmsDataCls> { };
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select DataId,Subject,RelationTypeName from TableRelationData " +
                "   join TableData on TableData.DataId=frkRelDataId" +
                "   join TableRelationType on TableRelationType.RelationTypeId=frkRelationTypeId" +
                " where frkSrcDataId=@DataId";
            DataSet dsResult =
                DBService.GetDataSet(null, Query, new DbParam[] { new DbParam("DataId", DataId) });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return ResCmsData;
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]); ;
            dsResult.Clear();
            dsResult.Dispose();
            for (int iIndex = 0; iIndex < CmsDatas.Length; iIndex++)
            {
                ResCmsData.Add(CmsDatas[iIndex]);
                ResCmsData = GetDocumentRelation(SiteId, CmsDatas[iIndex].DataId, ResCmsData);
            }

            return ResCmsData;
        }



        public override Collection<CmsDataCls> GetDocumentRelationRevert(string SiteId, string DataId, Collection<CmsDataCls> ResCmsData)
        {
            if (ResCmsData == null) ResCmsData = new Collection<CmsDataCls> { };
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select DataId,Subject,RelationTypeName from TableRelationData " +
                "   join TableData on TableData.DataId=frkSrcDataId" +
                "   join TableRelationType on TableRelationType.RelationTypeId=frkRelationTypeId" +
                " where frkRelDataId=@DataId";
            DataSet dsResult =
                DBService.GetDataSet(null, Query, new DbParam[] { new DbParam("DataId", DataId) });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return ResCmsData;
            }
            CmsDataCls[] CmsDatas = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]); ;
            dsResult.Clear();
            dsResult.Dispose();
            for (int iIndex = 0; iIndex < CmsDatas.Length; iIndex++)
            {
                ResCmsData.Add(CmsDatas[iIndex]);
                ResCmsData = GetDocumentRelation(SiteId, CmsDatas[iIndex].DataId, ResCmsData);
            }

            return ResCmsData;
        }

        //public override void GetPdfDocumentUrl(string SiteId, string DataId)
        //{
        //    CmsDataCls OCmsData = CreateCmsDataModel(SiteId, DataId);
        //    SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
        //    string Url=OCmsData.GetAttachDocUrlWithRoot(SiteId,WebConfig.HttpDataRoot(OSiteParam));
        //    return Url;
        //}


        public override void SendForPublish(
            string SiteId,
            string DocumentId)
        {
            bool HasCommit = false;
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, DocumentId);
            if (OCmsData.IsPublic == 1)
            {
                throw new Exception("Đã phát hành văn bản không cần phải khởi tạo quy trình duyệt");
            }
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            IDbTransaction Trans = DBService.BeginTransaction();
            try
            {
                string Query = " Update TableData set NeedApproved=1 where DataId=@DataId";
                DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
                    new DbParam("DataId",DocumentId)
                });

                string GroupBatchId = System.Guid.NewGuid().ToString();
                string BatchId = GroupBatchId;
                //start workflow
                bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, DocumentId);
                if (HasStarted) throw new Exception("Đã phát hành quy trình rồi! Xin vui lòng thực hiện trong quy trình");
                WorkflowUtilities.StartWorkflow(
                    (SqlTransaction)Trans,
                    SiteId,
                    "3ad568d2-ba77-4814-bd07-49d3df759c90",
                    WebSessionUtility.GetCurrentLoginUser().AssetCode,
                    DocumentId,
                    WebSessionUtility.GetCurrentLoginUser().RoleId,
                    GroupBatchId,
                    BatchId,
                    WebSessionUtility.GetCurrentLoginUser().LoginName,
                    WebSessionUtility.GetCurrentLoginUser().FullName,
                    OCmsData.Subject,
                    OCmsData.DataType,
                    "");


                Trans.Commit();
                HasCommit = true;
                OCmsData.NeedApproved = 1;
                SaveXml(Trans, SiteId, OCmsData.AssetCode, OCmsData.frkGroupDataId, OCmsData.EntryDate, OCmsData.DataId);
            }
            catch (Exception ex)
            {
                if (!HasCommit)
                {
                    Trans.Rollback();
                }
                throw (ex);
            }
        }



        public override CmsDataCls[] ReadingCmsDataForPublish(
            string SiteId,
            string GroupDataId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebConfig.GetAssetCode(OSiteParam);// WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                    " select *,DocTypeName,DocFieldName,DocReleaseFromName,DocSignerName from TableData  " +
                    "       join TableGroupData on GroupDataId=frkGroupDataId  " +
                    "       left outer join TableDocType on TableDocType.DocTypeId=frkDocTypeId" +
                    "       left outer join TableDocField on TableDocField.DocFieldId=frkDocFieldId" +
                    "       left outer join TableDocSigner on TableDocSigner.DocSignerId=frkDocSignerId" +
                    "       left outer join TableDocReleaseFrom on TableDocReleaseFrom.DocReleaseFromId=TableData.frkDocReleaseFromId" +
                    "     where NeedApproved=1 and IsPublic<>1 and TableData.AssetCode=@AssetCode and TableData.frkGroupDataId=@GroupDataId";

            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("GroupDataId", GroupDataId),
                    });

            CmsDataCls[] CmsData = CmsDataParser.ParseFromDataTable(dsResult.Tables[0]);
            return CmsData;
        }

        public override void SyncGroupDataCategory(string SiteId, Collection<GroupDataCategoryCls> GroupDataCategories)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            IDbTransaction Trans = DBService.BeginTransaction();
            try
            {

                for (int iIndex = 0; iIndex < GroupDataCategories.Count; iIndex++)
                {
                    string MainId = GroupDataCategories[iIndex].frkDataLanguageId + "-" + GroupDataCategories[iIndex].MapId;

                    try
                    {
                        DBService.Insert(Trans, "TableGroupDataCategory", new DbParam[]{
                            new DbParam("GroupDataCategoryId", MainId),
                            new DbParam("MapId",GroupDataCategories[iIndex].MapId),
                            new DbParam("frkGroupDataId",GroupDataCategories[iIndex].frkGroupDataId),
                            new DbParam("frkDataLanguageId",GroupDataCategories[iIndex].frkDataLanguageId),
                            new DbParam("Name",GroupDataCategories[iIndex].Name),
                            new DbParam("frkGroupDataCategoryId",null),
                            new DbParam("SortIndex",iIndex+1),
                        });
                    }
                    catch (Exception ex)
                    {
                        ex.Source = "";
                    }
                    //update no
                    string UpdateQuery = " Update TableGroupDataCategory set Name=@Name where GroupDataCategoryId=@GroupDataCategoryId";
                    DBService.ExecuteNonQuery(Trans, UpdateQuery,
                        new DbParam[]{
                            new DbParam("GroupDataCategoryId", MainId),
                            new DbParam("Name",GroupDataCategories[iIndex].Name),
                        });

                    //doan nay nhet thang con vao
                    for (int iIndexSub = 0; iIndexSub < GroupDataCategories[iIndex].SubGroupDataCategories.Count; iIndexSub++)
                    {
                        string SubId = GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].frkDataLanguageId + "-" + GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].GroupDataCategoryId;

                        try
                        {
                            DBService.Insert(Trans, "TableGroupDataCategory", new DbParam[]{
                                new DbParam("GroupDataCategoryId",SubId),
                                new DbParam("MapId",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].GroupDataCategoryId),
                                new DbParam("frkGroupDataId",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].frkGroupDataId),
                                new DbParam("frkDataLanguageId",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].frkDataLanguageId),
                                new DbParam("Name",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].Name),
                                new DbParam("frkGroupDataCategoryId",MainId),
                                new DbParam("SortIndex",iIndexSub+1),
                            });
                        }
                        catch (Exception ex)
                        {
                            ex.Source = "";
                        }
                        //update no
                        //DBService.Update(Trans, "TableGroupDataCategory", "GroupDataCategoryId", GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].GroupDataCategoryId,
                        //    new DbParam[]{
                        //    new DbParam("Name",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].Name),
                        //});

                        UpdateQuery = " Update TableGroupDataCategory set Name=@Name where GroupDataCategoryId=@GroupDataCategoryId";
                        DBService.ExecuteNonQuery(Trans, UpdateQuery,
                            new DbParam[]{
                            new DbParam("GroupDataCategoryId", SubId),
                            new DbParam("Name",GroupDataCategories[iIndex].SubGroupDataCategories[iIndexSub].Name),
                        });
                    }
                }
                Trans.Commit();
            }
            catch (Exception ex)
            {
                Trans.Rollback();
                throw (ex);
            }
        }

        public override GroupDataCategoryCls[] ReadingGroupDataCategory(string SiteId, string DataLanguageId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                     " select * from TableGroupDataCategory where frkDataLanguageId=@DataLanguageId and frkGroupDataCategoryId is null order by SortIndex; " +
                     " select * from TableGroupDataCategory where frkDataLanguageId=@DataLanguageId and not frkGroupDataCategoryId is null order by SortIndex; ";
            DataSet dsResult =
                      DBService.GetDataSet(null, Query,
                      new DbParam[] 
                    { 
                        new DbParam("DataLanguageId", DataLanguageId),
                    });

            GroupDataCategoryCls[] GroupDataCategories = new GroupDataCategoryCls[dsResult.Tables[0].Rows.Count];
            for (int iIndex = 0; iIndex < dsResult.Tables[0].Rows.Count; iIndex++)
            {
                GroupDataCategories[iIndex] = new GroupDataCategoryCls();
                GroupDataCategories[iIndex].frkDataLanguageId = DataLanguageId;
                GroupDataCategories[iIndex].frkGroupDataId = (string)dsResult.Tables[0].Rows[iIndex]["frkGroupDataId"];
                GroupDataCategories[iIndex].GroupDataCategoryId = (string)dsResult.Tables[0].Rows[iIndex]["GroupDataCategoryId"];
                GroupDataCategories[iIndex].Name = (string)dsResult.Tables[0].Rows[iIndex]["Name"];
                GroupDataCategories[iIndex].SubGroupDataCategories = new Collection<GroupDataCategoryCls> { };

                DataView dv = new DataView(dsResult.Tables[1], "frkGroupDataCategoryId='" + GroupDataCategories[iIndex].GroupDataCategoryId + "'", "", DataViewRowState.CurrentRows);
                for (int iSub = 0; iSub < dv.Count; iSub++)
                {
                    GroupDataCategoryCls OGroupDataCategory = new GroupDataCategoryCls();
                    OGroupDataCategory.frkDataLanguageId = DataLanguageId;
                    OGroupDataCategory.frkGroupDataId = (string)dv[iSub]["frkGroupDataId"];
                    OGroupDataCategory.GroupDataCategoryId = (string)dv[iSub]["GroupDataCategoryId"];
                    OGroupDataCategory.Name = (string)dv[iSub]["Name"];
                    OGroupDataCategory.frkGroupDataCategoryId = GroupDataCategories[iIndex].GroupDataCategoryId;

                    GroupDataCategories[iIndex].SubGroupDataCategories.Add(OGroupDataCategory);
                }
            }


            return GroupDataCategories;
        }

        public override GroupDataCategoryCls[] ReadingGroupDataCategoryForWorkflowAction(string SiteId, string DataLanguageId, string RoleId, string UserId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                     " select *,TotalTasks=0 into #temp_x from TableGroupDataCategory where frkDataLanguageId=@DataLanguageId and GroupDataCategoryId in (select frkGroupDataCategoryId from TableDataCategory where frkDataId in (select RecordId from TableWorkflowAction where [sent]=0 and ProcessDone=0 and EmployeeId=@EmployeeId and toRole=@RoleId) ) order by SortIndex; " +
                     " Update #temp_x set TotalTasks=" +
                     "  (" +
                     "      select count(id) from TableDataCategory" +
                     "              join TableWorkflowAction on TableWorkflowAction.RecordId=frkDataId" +
                     "       where frkGroupDataCategoryId=GroupDataCategoryId and [sent]=0 and ProcessDone=0 and EmployeeId=@EmployeeId and toRole=@RoleId" +
                     "  );" +
                     " select * from #temp_x; " +
                     " select *,TotalTasks=0 into #temp_y from TableGroupDataCategory " +
                     "      where frkDataLanguageId=@DataLanguageId and frkGroupDataCategoryId is null " +
                     "          and " +
                     "          (" +
                     "              GroupDataCategoryId in (select frkGroupDataCategoryId from #temp_x where not frkGroupDataCategoryId is null)" +
                     "              or GroupDataCategoryId in (select GroupDataCategoryId from #temp_x where frkGroupDataCategoryId is null)" +
                     "          );" +//lay xem nhung thang cha nao co
                     " drop table #temp_x; " +

                     " Update #temp_y set TotalTasks=" +
                     "  (" +
                     "      select count(id) from TableDataCategory" +
                     "              join TableWorkflowAction on TableWorkflowAction.RecordId=frkDataId" +
                     "       where frkGroupDataCategoryId=GroupDataCategoryId and [sent]=0 and ProcessDone=0 and EmployeeId=@EmployeeId and toRole=@RoleId" +
                     "  );" +

                     " select * from #temp_y;" +
                     " drop table #temp_y";
            DataSet dsResult =
                      DBService.GetDataSet(null, Query,
                      new DbParam[] 
                    { 
                        new DbParam("DataLanguageId", DataLanguageId),
                        new DbParam("EmployeeId", UserId),
                        new DbParam("RoleId", RoleId),
                    });

            DataTable dtMain = dsResult.Tables[1];
            GroupDataCategoryCls[] GroupDataCategories = new GroupDataCategoryCls[dtMain.Rows.Count];
            for (int iIndex = 0; iIndex < dtMain.Rows.Count; iIndex++)
            {
                GroupDataCategories[iIndex] = new GroupDataCategoryCls();
                GroupDataCategories[iIndex].frkDataLanguageId = DataLanguageId;
                GroupDataCategories[iIndex].frkGroupDataId = (string)dtMain.Rows[iIndex]["frkGroupDataId"];
                GroupDataCategories[iIndex].GroupDataCategoryId = (string)dtMain.Rows[iIndex]["GroupDataCategoryId"];
                GroupDataCategories[iIndex].Name = (string)dtMain.Rows[iIndex]["Name"];
                GroupDataCategories[iIndex].TotalTasks = (int)dtMain.Rows[iIndex]["TotalTasks"];
                GroupDataCategories[iIndex].SubGroupDataCategories = new Collection<GroupDataCategoryCls> { };
                DataView dvSub = new DataView(dsResult.Tables[0], "frkGroupDataCategoryId='" + GroupDataCategories[iIndex].GroupDataCategoryId + "'", "", DataViewRowState.CurrentRows); ;
                int TotalTasks = 0;
                for (int iIndexSub = 0; iIndexSub < dvSub.Count; iIndexSub++)
                {
                    string SubId = (string)dvSub[iIndexSub]["GroupDataCategoryId"];
                    if (!SubId.Equals(GroupDataCategories[iIndex].GroupDataCategoryId))
                    {
                        GroupDataCategoryCls OGroupDataCategory = new GroupDataCategoryCls();
                        OGroupDataCategory.frkDataLanguageId = DataLanguageId;
                        OGroupDataCategory.frkGroupDataId = (string)dvSub[iIndexSub]["frkGroupDataId"];
                        OGroupDataCategory.GroupDataCategoryId = SubId;
                        OGroupDataCategory.Name = (string)dvSub[iIndexSub]["Name"];
                        OGroupDataCategory.TotalTasks = (int)dvSub[iIndexSub]["TotalTasks"];
                        OGroupDataCategory.frkGroupDataCategoryId = GroupDataCategories[iIndex].GroupDataCategoryId;
                        GroupDataCategories[iIndex].SubGroupDataCategories.Add(OGroupDataCategory);
                        TotalTasks = TotalTasks + OGroupDataCategory.TotalTasks;
                    }
                }
                //GroupDataCategories[iIndex].TotalTasks = TotalTasks;
            }

            //GroupDataCategoryCls[] GroupDataCategories = new GroupDataCategoryCls[dsResult.Tables[0].Rows.Count];
            //for (int iIndex = 0; iIndex < dsResult.Tables[0].Rows.Count; iIndex++)
            //{
            //    GroupDataCategories[iIndex] = new GroupDataCategoryCls();
            //    GroupDataCategories[iIndex].frkDataLanguageId = DataLanguageId;
            //    GroupDataCategories[iIndex].frkGroupDataId = (string)dsResult.Tables[0].Rows[iIndex]["frkGroupDataId"];
            //    GroupDataCategories[iIndex].GroupDataCategoryId = (string)dsResult.Tables[0].Rows[iIndex]["GroupDataCategoryId"];
            //    GroupDataCategories[iIndex].Name = (string)dsResult.Tables[0].Rows[iIndex]["Name"];
            //    GroupDataCategories[iIndex].TotalTasks = (int)dsResult.Tables[0].Rows[iIndex]["TotalTasks"];
            //    GroupDataCategories[iIndex].SubGroupDataCategories = new Collection<GroupDataCategoryCls> { };
            //}


            return GroupDataCategories;
        }

        public override DataSaveHistoryCls[] ReadingDataSaveHistory(string SiteId, string CmsDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);

            string Query =
                  " select * from TableDataSaveHistory where DataId=@DataId order by SaveDate DESC";

            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("DataId", CmsDataId)
                    });

            DataSaveHistoryCls[] DataSaveHistories = DataSaveHistoryParser.ParseFromDataTable(dsResult.Tables[0]);
            return DataSaveHistories;
        }

        public override StudentSurveyCls[] ReadingVotedStudentList(string SiteId, string GroupDataId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select * from TableStudentSurvey where frkSurveyId=@SurveyId order by SurveyDate";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("SurveyId", GroupDataId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new StudentSurveyCls[0];
            }
            StudentSurveyCls[] StudentSurveys = StudentSurveyParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return StudentSurveys;
        }

        public override StudentSurveyCls CreateStudentSurveyModel(string SiteId, string StudentSurveyId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select * from TableStudentSurvey where StudentSurveyId=@StudentSurveyId";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("StudentSurveyId", StudentSurveyId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            StudentSurveyCls OStudentSurvey = StudentSurveyParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return OStudentSurvey;
        }

        public override GroupDataFolderCls CreateGroupDataFolderModel(IDbTransaction Trans, string SiteId, string GroupDataFolderId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(Trans, "select TableGroupDataFolder.* from TableGroupDataFolder " +
                                               "     where GroupDataFolderId=@GroupDataFolderId",
                    new DbParam[] 
                    { 
                        new DbParam("GroupDataFolderId", GroupDataFolderId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            GroupDataFolderCls OGroupDataFolder = GroupDataFolderParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);

            dsResult.Clear();
            dsResult.Dispose();
            return OGroupDataFolder;
        }

        public override GroupDataFolderCls[] ReadingGroupDataFolder(
            IDbTransaction Trans,
            string SiteId,
            string GroupDataId,
            string ParentGroupDataFolderId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                "select TableGroupDataFolder.* from TableGroupDataFolder where frkGroupDataId='" + GroupDataId + "' ";
            if (!string.IsNullOrEmpty(ParentGroupDataFolderId))
            {
                Query += " and frkParentGroupDataFolderId='" + ParentGroupDataFolderId + "' ";
            }
            else
            {
                Query += " and frkParentGroupDataFolderId is null ";
            }
            Query += " order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(Trans, Query, null);
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupDataFolderCls[0];
            }
            GroupDataFolderCls[] OGroupDataFolder = GroupDataFolderParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return OGroupDataFolder;
        }

        public override string AddGroupDataFolder(
            IDbTransaction Trans,
            string SiteId,
            string GroupDataId,
            string ParentGroupDataFolderId,
            string FolderName,
            int SortIndex)
        {
            string GroupDataFolderId = System.Guid.NewGuid().ToString();
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            if (string.IsNullOrEmpty(ParentGroupDataFolderId)) ParentGroupDataFolderId = null;
            DBService.Insert(Trans, "TableGroupDataFolder", new DbParam[]{
                new DbParam("GroupDataFolderId",GroupDataFolderId),
                new DbParam("frkGroupDataId",GroupDataId),
                new DbParam("FolderName",FolderName),
                new DbParam("Description",""),
                new DbParam("frkParentGroupDataFolderId",ParentGroupDataFolderId),
                new DbParam("SortIndex",SortIndex),
            });
            return GroupDataFolderId;
        }

        public override string SaveGroupDataFolder(
            IDbTransaction Trans,
            string SiteId,
            string GroupDataId,
            string GroupDataFolderId,
            string FolderName,
            int SortIndex)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Update(Trans, "TableGroupDataFolder", "GroupDataFolderId", GroupDataFolderId, new DbParam[]{
                new DbParam("FolderName",FolderName),
                new DbParam("SortIndex",SortIndex),
            });
            return GroupDataFolderId;
        }

        public override void DeleteGroupDataFolder(IDbTransaction Trans, string SiteId, string GroupDataId, string GroupDataFolderId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = "Delete from TableGroupDataFolder where GroupDataFolderId=@GroupDataFolderId";
            DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
                new DbParam("GroupDataFolderId",GroupDataFolderId),
            });
        }

        public override void MoveGroupDataFolder(
            IDbTransaction Trans,
            string SiteId,
            string GroupDataId,
            string MoveGroupDataFolderId,
            string ToGroupDataFolderId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = " Update TableGroupDataFolder set frkParentGroupDataFolderId=@ToGroupDataFolderId where GroupDataFolderId=@MoveGroupDataFolderId";
            DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
                new DbParam("MoveGroupDataFolderId",MoveGroupDataFolderId),
                new DbParam("ToGroupDataFolderId",ToGroupDataFolderId),
            });
        }

        public override void MoveDocumentToGroupDataFolder(
            IDbTransaction Trans,
            string SiteId,
            string GroupDataId,
            string MoveDocumentId,
            string ToGroupDataFolderId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            CmsDataCls OCmsData = CreateCmsDataModel(null, SiteId, MoveDocumentId);
            string DataBelongGroupDataFolderId = System.Guid.NewGuid().ToString();
            string Query =
                " Delete from TableDataBelongGroupDataFolder where frkDataId=@DataId; " +
                " Update TableData set frkGroupDataFolderId=@GroupDataFolderId where DataId=@DataId; " +
                " Insert into TableDataBelongGroupDataFolder(DataBelongGroupDataFolderId, frkGroupDataFolderId, frkDataId) values (@DataBelongGroupDataFolderId, @GroupDataFolderId, @DataId)";
            DBService.ExecuteNonQuery(Trans, Query, new DbParam[]{
                new DbParam("DataBelongGroupDataFolderId",DataBelongGroupDataFolderId),
                new DbParam("GroupDataFolderId",ToGroupDataFolderId),
                new DbParam("DataId",MoveDocumentId),
            });

            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            SaveXml(null, SiteId, OCmsData.AssetCode, GroupDataId, OCmsData.EntryDate, OCmsData.DataId);

        }
    }
}

